[Tutor] Using Python for accurate calculations

Alan Gauld alan.gauld at btinternet.com
Tue May 13 01:01:36 CEST 2008


"Gloom Demon" <gloomdemon at gmail.com> wrote

> I am working on a function which is going to calculate correlation
> between two given sets of numbers.
>
> Example:
> x=[10.0, 10.8, 11.3, 10.0, 10.1, 11.1, 11.3, 10.2, 13.5, 12.3, 14.5, 
> 11.0,
> y=[0.70, 0.73, 0.75, 0.70, 0.65, 0.65, 0.70, 0.61, 0.70, 0.63, 0.70, 
> 0.65,
>
> However Python stores these numbers like this:
>>>> x
> [10.0, 10.800000000000001, 11.300000000000001, 10.0, 10.1, 11.1,

> The extra digits added by Python are adding error probability

The digits aren't really added by Python they are just the nearest
equivalent to your decimal numbers in binary. It will happen in
any computer program that uses standard float types (even a
pocket calculator!)

This is one reason not to use floats for finance calculations!

There are several ways around it.

1) Multiply up your numbers to integer values - in your case
multiplying by 100 (or 1000) would work. - Easy with a list
comprehension.

2) Use the decimal module for  fixed decimals. (BCD if you like)

3) Set limits and work within +/- delta of your final values.

Much depends on whether the errors are affecting the results
or only the display of the results. The display can be fixed via
formatted printing, the actual values will need options 1-3.

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld 




More information about the Tutor mailing list