Answer the question
In order to leave comments, you need to log in
Python: Why is there an error in the process of summing decimals in the middle of an interval?
Hello, dear habravchane.
The topic is indicated in the title. First grade code. BUT in the process of summation (increasing values by a constant), an error accumulates, which then disappears.
>>> interv = 10
>>> start = -2
>>> stop = 2
>>> mas =[]
>>> step = 0.4
>>> mas.append(start)
>>> for i in range(1, interv):
mas.append(mas[i-1]+step)
>>> mas
[-2, -1.6, -1.2000000000000002, -0.8000000000000002, -0.40000000000000013, -1.1102230246251565e-16, 0.3999999999999999, 0.7999999999999999, 1.2, 1.6]
Answer the question
In order to leave comments, you need to log in
In fact, the described problem can be illustrated more simply:
>>> 0.5+2.7, 0.4+2.8
(3.2, 3.1999999999999997)
abs(a-b)<eps
, where a
andb
are floating point numbers, and eps is some negligible value. In fact, I think that even the minimum value of this value can be calculated so that it covers all the troubles with rounding binary digits.
In my opinion, there is nothing special here. Normal error for real numbers.
Quite a normal situation for floating point numbers. Want to get rid of - use decimal.
The reason for this strange behavior is the limitation of the hardware that implements the real math. Example:
>>> f = 1/3.0
>>> f
0.3333333333333333
>>> '%4.2f' % f
'0.33'
>>>
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question