Correct incorrect module return [duplicate]

2

Mathematically speaking why it happens and how to correct the following "error" in python:

>>>10.53 % 1
0.5299999999999994

I'd like to understand how python works to get this value, why this occurs.

In fact the duplicate possible formats the output via the command print .

But I would like to work without print ...

View

    
asked by anonymous 13.10.2017 / 06:26

2 answers

3

The 'problem' not only in python, it happens in many other languages, some do not 'demonstrate' because they treat internally the result internally. This has been a subject since the early days of computing, and has to do with a binary approximation of numbers instead of decimal.

KNOW MORE (python)

LEARN MORE (general PT)

KNOW MORE (EN GENERAL)

In order to perform mathematical operations accurately and not just format the output you can use the decimal module

from decimal import Decimal

value = Decimal('10.53') % 1
print(value) # 0.53

DEMONSTRATION

    
13.10.2017 / 08:51
2

This happens because some numbers can not be represented exactly in floating-point notation.

What you can do in this case is to approximate the number to a certain number of decimal places when you are to show the user:

print('%0.2f' % (10.53 % 1))

The biggest problem is if you need to do several operations with floating points in sequence. In this case the error may increase more and more. Depending on the case, you can work with integers, multiplying the values by 100 for example, and when you show the final result, divide by 100 again and round. By doing this the error will be minimized.

    
13.10.2017 / 06:41