Is there a fast Way to return Sin and Cos of the same value in Python?
I compared the suggested solution with perfplot and found that nothing beats calling sin
and cos
explicitly.
Code to reproduce the plot:
import perfplotimport numpy as npdef sin_cos(x): return np.sin(x), np.cos(x)def exp_ix(x): eix = np.exp(1j * x) return eix.imag, eix.realdef 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, cosperfplot.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",)
You can use complex numbers and the fact that e i · φ = cos(φ) + i · sin(φ).
import numpy as npfrom cmath import rectnprect = np.vectorize(rect)x = np.arange(2 * np.pi, step=0.01)c = nprect(1, x)a, b = c.imag, c.real
I'm using here the trick from https://stackoverflow.com/a/27788291/674064 to make a version of cmath.rect()
that'll accept and return NumPy arrays.
This doesn't gain any speedup on my machine, though:
c = nprect(1, x)a, b = c.imag, c.real
takes about three times the time (160μs) that
a, b = np.sin(x), np.cos(x)
took in my measurement (50.4μs).
You could take advantage by the fact that tan(x) contains both sin(x) and cos(x) function. So you could use the tan(x) and retrieve cos(x) ans sin(x) using the common transformation function.