I got this question. Write a function cos_x_crossings(begin, end, skip), where the input parameters are entered and returns x-points as a list that crosses the x-axis.(x-value that just before it crosses) I am not allowed to use for or while loop. Required to use NumPy.
test 1
import math
ans = cos_x_crossings(0, 4 * math.pi, 0.01)
for val in ans:
print(round(val, 2))
result 1
1.57
4.71
7.85
10.99
test 2
import math
ans = cos_x_crossings(0, 2 * math.pi, 0.1)
for val in ans:
print(round(val, 2))
result 2
1.5
4.7
CodePudding user response:
Since we already know that cos(x) is zero if and only x is of the form pi/2 k pi, all you have to do is call numpy.arange
with the correct parameters to generate the output array.
import numpy as np
def cos_x_crossings(xstart, xstop, xstep):
ystart = (np.trunc((xstart - np.pi/2) / np.pi) 0.5) * np.pi
ystop = xstop
ystep = np.pi
return (np.arange(ystart, ystop, ystep) // xstep) * xstep
print( cos_x_crossings(0, 4 * np.pi, 0.01) )
# [ 1.57 4.71 7.85 10.99]
print( cos_x_crossings(0, 2 * np.pi, 0.1) )
# [1.5 4.7]