Can anyone explain this subtraction and summation in python?

I am a little confused about how this subtraction and summation work as follows:

A = 5 B = 0.1 C = A+BA 

And I found the answer 0.099999999999999645. Why is the answer not 0.1?

+4
source share
5 answers

This is a floating point rounding error. There is a really good tutorial on floating point numbers on the Python website that explains what it is and why it happens.

If you want an accurate result, you can:

  • try using decimal
  • Format the result to display the specified number of decimal places (this does not correct the rounding error):

    print "%.2f"%C

I also recommend reading "What Every Computer Scientist Should Know About Floating-Point Arithmetic" from Brian's answer.

+3
source

Why is the answer not 0.1?

Floating-point numbers are not accurate enough to get an answer. But the holy cow is always there!

I recommend that you read " What Every Computer Scientist Should Know About Floating-Point Arithmetic "

+2
source

You see a floating point arithmetic artifact that does not have infinite precision. See this article for a full description of how FP maths works and why you see rounding errors.

+2
source

This is due to the so-called epsilon value. This means that from x to x+E each floating point number is considered equal to x . You can read something about this value in this Q & A in python, this epsilon ( E ) value depends on the value of the number, you can always get it from numpy.spacing(x)

+2
source

Computers use binary numbers to store information. Integers can be stored exactly, but fractional numbers are usually stored as "floating point numbers".

There are numbers that are easily written in base-10, which cannot be accurately represented in binary floating-point format, and 0.1 is a number.

You can store numbers accurately and work with numbers accurately. For example, the number 0.1 can be saved as 1 / 10 , in other words, saved as a numerator (1) and a denominator (10) with the understanding that the numerator is divisible by a denominator. Then a correctly written math library can work with these fractions and do the math for you. But this is much, much slower than just using floating point numbers, so this is not so often used. (And I think that in the banking sector they usually use integers instead of a floating point to store money, $ 1.23 can be saved as 123 with an implicit two decimal places. When working with money, a floating point is not accurate enough!)

+2
source

Source: https://habr.com/ru/post/1486968/


All Articles