Thom
Thom

Reputation: 155

How to change numerical precision in python?

If I write 1e-15 in python, python can distinguish that number from zero but if I write 1e-16 python can not distinguish that number from 0. So python is precise up to 16th digit. Is there a way to reduce this precision to for example 10 digits? How? Can I make calculations with some

Thanks for any help.

Upvotes: 1

Views: 1429

Answers (1)

Pavel Vergeev
Pavel Vergeev

Reputation: 3390

If you want precise arithmetic in your computations, it is highly discouraged to use the default float type. See Floating Point Arithmetic: Issues and Limitations section of the official documentation.

This is why you will be much better off with decimal module. It has several ways to control the precision.

Here we change the precision globally:

>>> from decimal import *
>>> getcontext().prec = 6
>>> Decimal(1) / Decimal(7)
Decimal('0.142857')
>>> getcontext().prec = 28
>>> Decimal(1) / Decimal(7)
Decimal('0.1428571428571428571428571429')

And here we do it for a single number:

>> Decimal('0.1428571428571428571428571429').quantize('0.01')
Decimal('0.14')

You can find more examples in the docs.

Upvotes: 2

Related Questions