Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a fast Way to return Sin and Cos of the same value in Python?

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?

like image 763
rylirk Avatar asked Sep 04 '15 11:09

rylirk


People also ask

How do you do Arccos in Python?

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.

What is Arccos Numpy?

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.


1 Answers

I compared the suggested solution with perfplot and found that nothing beats calling sin and cos explicitly.

enter image description here

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",
)
like image 162
Nico Schlömer Avatar answered Sep 26 '22 01:09

Nico Schlömer