String to Float, without introducing errors

Greg Ewing greg.ewing at canterbury.ac.nz
Sun Dec 18 19:10:16 EST 2022


On 19/12/22 9:24 am, Stefan Ram wrote:
>  So what's the time until a mass of one gram
>  arrives at the ground versus a mass of ten grams? I think
>  one needs "Decimal" to calculate this!

Or you can be smarter about how you calculate it.

Differentiating t with respect to m gives

dt/dm = -0.5 * sqrt(2 * s * r**2 / (G * (M + m)**3))

which, since m is much smaller than M, is approximately

    -0.5 * sqrt(2 * s * r**2 / (G * M**3))

So

 >>> G = 6.6743015E-11
 >>> r = 6.371E6
 >>> M = 5.9722E24
 >>> dtdm = -0.5 * sqrt(2*s*(r**2) / (G * M**3))
 >>> dtdm * (1/1000 - 10/1000)
3.4004053539917275e-28

which agrees with your Decimal calculation to 3 digits,
and should be as precise as the input numbers (about
4 digits in this case).

This is a good example of why it's important to choose
an appropriate numerical algorithm!

-- 
Greg


More information about the Python-list mailing list