Floating point overflow and underflow

Rob Gaddi rgaddi at highlandtechnology.invalid
Tue Jan 7 20:23:30 EST 2020


On 1/7/20 3:47 PM, Shashank Tiwari wrote:
> In Python3 an operation as follows:
>>>> 10135.1941 * (10**8)
> gives the result: 1013519410000.0001
> 
> Similarly, using the pow function also gives the same overflow/underflow
> error.
>>>> 10135.1941 * pow(10,8)
> 1013519410000.0001
> 
> Like multiplication, division of large or very small floating point numbers
> gives similar overflow/underflow errors.
> 
> Usage of Decimal doesn't seem to fix it either.
>>>> from decimal import *
>>>> Decimal(10135.1941 * pow(10,8))
> Decimal('1013519410000.0001220703125')
>>>> Decimal(10135.1941)*pow(10,8)
> Decimal('1013519410000.000061700120568')
>>>> Decimal(10135.1941) * Decimal(pow(10,8))
> Decimal('1013519410000.000061700120568')
>>>> Decimal(10135.1941 * (10**8))
> Decimal('1013519410000.0001220703125')
> 
> How could one do high precision multiplication and division of floating
> points numbers (decimals) in Python3 without any overflow/underflow errors?
> 
> Thanks, Shanky
> 

You've already polluted your Decimal with floating-point roundoff error before 
you even multiply it in any of your examples.

 >>> Decimal(10135.1941)
Decimal('10135.1941000000006170012056827545166015625')

Initialize your Decimal from a string instead.

 >>> Decimal('10135.1941')
Decimal('10135.1941')
 >>> Decimal('10135.1941') * Decimal('1e8')
Decimal('1.01351941E+12')
 >>> float(_)
1013519410000.0


More information about the Python-list mailing list