Home > OS >  python adding zeroes and a random digit in floats
python adding zeroes and a random digit in floats

Time:02-16

Trying to add zeroes and a random digit in floats in Python.

I have a code that just loops through and shows the cumulative frequency at each step and the final sum should be 1 but it isn't working.

Here is the output:

0.11
0.197
0.279
0.35700000000000004
0.43000000000000005
0.502
0.569
0.6299999999999999
0.6829999999999999
0.723
0.761
0.794
0.8240000000000001
0.8520000000000001
0.8790000000000001
0.9040000000000001
0.9270000000000002
0.9470000000000002
0.9630000000000002
0.9770000000000002
0.9870000000000002
0.9961000000000002
1.0005000000000002
1.0032
1.0056
1.0077
1.0077

I think this is being caused by the long row of zeroes in some numbers like 0.35700000000000004 in the 4th one. Also, many values are changing like in the first step it should be 0.11 and not 0.197.

Example code:

for i in AlphabetWeights:
    count = i count
    print(count)

CodePudding user response:

This is not an arithmetic issue.. You can see that your truncation error is happening O(1e-16), as is expected. What you describe as an 'error' is on the order of 1e-3. You even see that your truncation error is cancelling out at times.. no way that your deviation of 0.0077 from the desired result 1.0 is due to floating-point arithmetic

like in the first step it should be 0.11 and not 0.197.

Check your code for bugs.. this is not floating-point arithmetic

CodePudding user response:

You can use Decimal in this case. The decimal module provides support for fast correctly-rounded decimal floating-point arithmetic. Check this link: Python Decimal

Check this code:

from decimal import *

getcontext().prec = 6

Decimal(1) / Decimal(7)
Decimal('0.142857')

getcontext().prec = 28

Decimal(1) / Decimal(7)
Decimal('0.1428571428571428571428571429')

for example:

x = 0.1
y = 0.1
z = 0.1

s = x   y   z

print(s)

the output will be :

0.30000000000000004

but

import decimal
from decimal import Decimal


x = Decimal('0.1')
y = Decimal('0.1')
z = Decimal('0.1')

s = x   y   z

print(s)

the output will be :

0.3
  • Related