Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 590
santiagobasulto Avatar asked Jun 01 '12 16:06

santiagobasulto


People also ask

Can we use trigonometric functions in Python?

Trigonometric calculations can be performed in python by using built-in functions defined in the math module. By using the math module in python, the number of lines in the code can be reduced to a minimum. We can either import the math module or use the dot operator with a math library to use trigonometric functions.

How do you show decimals in Python?

In Python, there are various methods for formatting data types. The %f formatter is specifically used for formatting float values (numbers with decimals). We can use the %f formatter to specify the number of decimal numbers to be returned when a floating point number is rounded up.

Can sin be a decimal?

Values of sin(a) and cos(a) are rational numbers only for particular angles (see Link ) so you can't store values of sin(a) or cos(a) as Decimals without losing precision.


2 Answers

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)
like image 166
kindall Avatar answered Oct 19 '22 22:10

kindall


Pi is an irrational number so it can't be represented exactly using a finite number of bits. However, you can use some library for symbolic computation such as sympy.

>>> sympy.sin(sympy.pi)
0

Regarding the second part of you question, if you want to use degrees instead of radians you can define a simple conversion function

def radians(x):
    return x * sympy.pi / 180

and use it as follows:

>>> sympy.sin(radians(180))
0
like image 24
vitaut Avatar answered Oct 19 '22 22:10

vitaut