Using decimals in math functions in Python

Question:

math is a Python module used by many to do a bit more advanced mathematical functions and 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? Isn’t there any way?

Asked By: KianFakheriAghdam

||

Answers:

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. Logarithm functions are generally expected to output some irrational result in typical usage. You could instead use a for loop and repeated division.

Answered By: spiderduckpig

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.

Answered By: SUTerliakov
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.