there! math
is a python module used by many to do a bit more advanced mathematical functions & using the decimal
module, one can calculate stuff correctly 1.2-1.1=0.0999~
, but using the decimal
type it's 0.1
.
My problem is that these two modules don't work well with each other. For example log(1000, 10)=2.9999~
but using a decimal
type gives the same result. How can I make these two work with each other? Do I need to implement my own functions? Is there no way?
CodePudding user response:
You have Decimal.log10
, Decimal.ln
and Decimal.logb
methods of each Decimal
instance, and many more (max
, sqrt
):
from decimal import Decimal
print(Decimal('0.001').log10())
# Decimal('-3')
print(Decimal('0.001').ln())
# Decimal('-6.907755278982137052053974364')
There are no trigonometry functions, though.
More advanced alternative for arbitrary-precision calculations is mpmath, available at PyPI. It won't provide you with sin
or tan
as well, of course, because sin(x)
is irrational for many x
values, and so storing it as Decimal
doesn't make sense. However, given fixed precision you can compute these functions via Tailor series etc. with mpmath
help. You can also do Decimal(math.sin(0.17))
to get some decimal holding something close to sine of 0.17 radians.
Also refer to official Decimal recipes.
CodePudding user response:
There is a log10 method in Decimal.
from decimal import *
a = Decimal('1000')
print(a.log10())
However it would make more sense to me to use a function that calculates the exact value of a logarithm if you're trying to solve logarithms with exact integer solutions. Logarithms are generally expected to output some irrational result in typical usage. This could be done using a for loop and repeated division.