r/learnpython • • 1h ago

On preventing the propagation of floating point error

TL:DR: how large is the floating point error on an mpmath float compared to the last exact significant digit?

I'm working on a program to calculate the value of various iterated maps.

The problem I was running into was, let's take, for the sake of simplicity a 2x mod 1 map with starting value at 0.4, after just a few iterations the values would deviate from the 0.4, 0.8, 0.6, 0.2, 0.4... cycle due to the spread of floating point error.

Now, I'm saving my data in a hdf5 file which uses numpy float64, which is more than acceptable for my use case as it gives me precision up to the 15th significant figure, so long as the overall behavior of the map is within that margin.

My solution to this was, working with mpmath, to take the input for the starting value as a string, calculate the value for the next iteration after converting in to an mpf, and then to run that into this function:

import mpmath as mp

def floaterrorfix (f):
    return mp.mpf (mp.nstr (f, int (mp.floor (mp.mp.prec * mp.log (2, 10)))))

Using an user submitted number of bits for the precision, also given that the number of digits of precision afforded by a float with b bites of mantissa is d = b*log_10(2), it basically removes the propagated error from the previous iteration and leaves me with the regular error for whatever the value/the number of bits used for storing was.

Now, I haven't noticed any error propagation while running maps for which I know the values (mainly cyclic ones) even millions of iterations in, but I think it should still be possible to get some, especially with more complex maps that involve more calculations per iteration (eg a standard map), all that is needed is for the error pre-iteration to be large enough to exceed into my supposedly "exact" figures after I apply the calculations and, given that I'd be running off of randomised start values and parameters I'd have no way to check if that was the case.

My solution to this would be getting the number of significant digits from the user input (or the 15 for standard float64 in case it has less than that) and set the precision so that, even the largest possible float error, will not exceed into those digits after I apply all calculations; this would also save me that pesky user submitted number of bits.

Before I do all that tho I want to make sure it's actually possible for the error to still propagate or if there are already checks in place within python/mpmath that would prevent this for any reasonable calculation and what the limit on that would be, also if I do need to apply my solution, I was unable to find a way to easily count the number of significant figures on a number stored in a string.

1 Upvotes

0 comments sorted by