I need to return the sin and cos values of every element in a large array. At the moment I am doing:
a,b=np.sin(x),np.cos(x)
where x is some large array. I need to keep the sign information for each result, so:
a=np.sin(x)
b=(1-a**2)**0.5
is not an option. Is there any faster way to return both sin and cos at once?
acos() function returns the arc cosine value of a number. The value passed in this function should be in between -1 to 1. Parameter:This method accepts only single parameters. Returns:This function returns the arc cosine value of a number.
arccos is a multivalued function: for each x there are infinitely many numbers z such that cos(z) = x . The convention is to return the angle z whose real part lies in [0, pi]. For real-valued input data types, arccos always returns real output.
I compared the suggested solution with perfplot and found that nothing beats calling sin
and cos
explicitly.
Code to reproduce the plot:
import perfplot
import numpy as np
def sin_cos(x):
return np.sin(x), np.cos(x)
def exp_ix(x):
eix = np.exp(1j * x)
return eix.imag, eix.real
def cos_from_sin(x):
sin = np.sin(x)
abs_cos = np.sqrt(1 - sin ** 2)
sgn_cos = np.sign(((x - np.pi / 2) % (2 * np.pi)) - np.pi)
cos = abs_cos * sgn_cos
return sin, cos
perfplot.save(
"out.png",
setup=lambda n: np.linspace(0.0, 2 * np.pi, n),
kernels=[sin_cos, exp_ix, cos_from_sin],
n_range=[2 ** k for k in range(20)],
xlabel="n",
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With