r/learnpython • u/LSD_SUMUS • 3d 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
u/Sufficient-Tale6131 2d ago
As far as I know nothing in mpmath tracks the error for you. A plain mpf just carries whatever rounding has piled up and gives no warning.
If you want an actual number for it, mpmath has interval arithmetic built in. Do from mpmath import iv, set iv.prec, and run the same map on iv.mpf('0.4') instead of mp.mpf. Every value is then an interval that's guaranteed to contain the exact result, and x.delta gives you its width. Once the width gets close to 1e-15 the float64 digits you save aren't trustworthy anymore, so you can check that every iteration instead of guessing a safe precision up front.
On 2x mod 1 you can watch the width double each step, starting from 112 bits it hits about 1e-16 after roughly 60 iterations. Same thing the other comment said about losing a bit per step, just measured.
1
u/LSD_SUMUS 2d ago edited 2d ago
I’ll have to look into iv, tho I don’t fully understand why what I’m doing is not going to work.
For reference I’m running most of my test calculations with 112 bit precision and getting no error propagation, even when running some irrational map (eg. a mouse map with starting value at 0 and a =4.9 and b=-0.58 having a period 8 cycle) they seem to stay consistent to the bit, so idk if those are just flukes or whatnot.
To my understanding, let’s say I have a number A, and when I run it into my map the theoretical result is B_t, but I get B, which has a flipped last bit, at 112 bits B_t - B < 2^-111= 2.8e-34, when I approximate B to the 33rd (tho I should arguably do 32nd in case more bits get flipped) digit with nstr, that flipped bit isn’t taken into consideration as the max possible error is too small to change that approximation, so when I take the string I get from that and plug it into mp.mpf I get the closest fp approximation to that and it unflips that last bit.
Sorry for the long reply really just trying to understand why the logic behind what I did fails
1
u/Sufficient-Tale6131 14h ago
Your logic holds for a single step, the catch is what it's holding against. When you nstr to 33 digits and parse it back, you get the 112-bit float nearest to that decimal, and that decimal was built from B (the computed value), not from B_t. So most of the time you just get B back unchanged. When the last bit does flip, it's because the decimal grid at 33 digits is a bit coarser than the binary grid at 112 bits, so the round trip can nudge you to a neighbour in either direction. It has no way of knowing which side the true value is on.
My guess for why your period-8 run stays identical to the bit: that cycle is attracting. On a stable orbit any tiny error gets pulled back toward the cycle every iteration, so it'll look like nothing propagates whatever you do. Try parameters where the map is chaotic and compare a 112-bit run against a 300-bit run of the same thing. They'll agree for a while and then split, and that's where iv would show the interval width blowing up.
1
u/Free-Good9203 3d ago
Two things that usually bite people on iterated chaotic maps:
Rounding back with `mp.nstr` at every step won't actually stop error growth—for a map like `2x mod 1`, you lose 1 bit of precision per iteration regardless (positive Lyapunov exponent). Instead of rounding inside the loop, keep `mp.mp.prec` high enough upfront for your total step count (`target_bits + steps * bits_lost_per_step`) and only cast to `float64` at the end when writing to HDF5. For purely rational maps like `2x mod 1`, Python's built-in `fractions.Fraction` is exact with zero drift.
For counting significant figures from a numeric string cleanly, `decimal.Decimal` handles scientific notation and trailing zeros well: `len(Decimal(s).normalize().as_tuple().digits)` (or skip `.normalize()` if trailing zeros in your input are intentionally significant).
2
u/TheRNGuy 3d ago
Just use
Decimal.How many numbers after dot do you need?