'Sin, cos etc for Python 2 Decimal?
In Python 2.6, I found that the Decimal equivalent of sqrt(pi) is
Decimal(pi).sqrt()
Is there anything like that for sin, cos or other (inverse) trigonometric functions?
The docs only mention how to calculate cos and sin computationally. Decimal(pi).cos() doesn't exist nor does from decimal import cos
Update: the problem with using the default trigonometric functions is that it defeats the point of using Decimal if I convert them from float and back every time I want to calculate something. (Also typing Decimal around every calculation is annoying, but I guess I could make a wrapper function)
Solution 1:[1]
Solution 2:[2]
The Decimal library was intended to support properly rounded, base-10 arithmetic primarily for financial calculations where precise control of rounding is required. It was not intended to be a general-purpose arbitrary precision library.
If you need a general purpose arbitrary precision library, look at mpmath or gmpy2.
Solution 3:[3]
The trig functions are in the math module
So:
>>> decimal.Decimal(math.cos(0.1))
Decimal('0.99500416527802570954008842818439006805419921875')
If you are looking for multi precision math library in Python that supports trig functions, Decimal isn't it. Take a look at mpmath. Mpmath supports trig function at arbitrary precision; decimal does not.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | dan-boa |
| Solution 2 | casevh |
| Solution 3 | Thruston |
