Fix incorrect module return

Asked

Viewed 81 times

2

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

>>>10.53 % 1
0.5299999999999994

I’d like to understand how the python works to obtain this value, why it occurs.

In fact to possible duplicate format the output via the command print.

But I’d like to work without the print...

Behold

  • Tries a = 10.53 % 1 and print("%.2f" % a) :)

  • It is a mistake to use the [error tag]. :)

  • 1

    As to why this error occurred, the matter is discussed in this question: https://answall.com/q/219211/64969

  • 1

    @Jeffersonquesado 2 fantastic answers, 1 more didactic other more technical, however maybe for me to get the answer I expected, the question should have been: "How is the module calculation" that by the way : >>>> https://answall.com/questions/93092/como-%C3%A9-made-o-c%C3%A1lculo-de-matem%C3%A1tica-do-m%C3%B3dulo-em-javascript Now doing a mix I’m beginning to understand... Vlw the tip;)

  • @Magichat the intention was only to show why the representation give these errors. In fact, to better understand the module is much more interesting this question that you linked

2 answers

3


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

LEARN MORE (python)

LEARN MORE (general EN)

LEARN MORE (GENERAL EN)

To be able to perform mathematical operations accurately and not just format the output you can use the module decimal

from decimal import Decimal

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

DEMONSTRATION

2

This is because some numbers cannot 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 showing the user:

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

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

  • Thanks for the attention, for now I have no way to evaluate, if it will serve my case, I believe not, because the operation is in the middle of the code, in the middle of a recursive function, in the middle of a loop... heheh But in reality, my problem is not round, but know how programming languages do to get these results...

Browser other questions tagged

You are not signed in. Login or sign up in order to post.