santiagobasulto - 2 years ago 112
Python Question

# Python: Decimals with trigonometric functions

I'm having a little problem, take a look:

``````>>> import math
>>> math.sin(math.pi)
1.2246467991473532e-16
``````

This is not what I learnt in my Calculus class (It was 0, actually)

So, now, my question:

I need to perform some heavy trigonometric calculus with Python. What library can I use to get correct values?

Can I use Decimal?

EDIT:

Sorry, What I mean is other thing.

What I want is some way to do:

``````>>> awesome_lib.sin(180)
0
``````

or this:

``````>>> awesome_lib.sin(Decimal("180"))
0
``````

I need a libraray that performs good trigonometric calculus. Everybody knows that sin 180° is 0, I need a library that can do that too.

`1.2246467991473532e-16` is close to 0 -- there are 16 zeroes between the decimal point and the first significant digit -- much as `3.1415926535897931` (the value of `math.pi`) is close to pi. The answer is correct to sixteen decimal places!
So if you want `sin(pi)` to equal 0, simply round it to a reasonable number of decimal places. 15 looks good to me and should be plenty for any application:
``````print round(math.sin(math.pi), 15)