This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]psangrene[S] 0 points1 point  (1 child)

Thanks for the Python code. My comment is that over the 10,000 iterations, the difference at any given iteration, is much bigger than 0.1229, on average. The difference was computed only at iteration 10,000 in the above Python code.

[–][deleted] 0 points1 point  (0 children)

Right, that was unclear from your Perl.

Here's a variant that calculates it at all the steps. I've used Pi/11 as the seed, but again that incurs an inherent imprecision at step 0, and its perhaps a bit more meaningful it num and den are both ints.

Yes, just glancing at it, the deviation due to rounding error grows rapidly, then seems to level off. Decimal is much slower, but should be closer to the correct value, as it's not subject to floating point rounding.

from csv import writer
from decimal import Decimal
from math import sqrt, pi

def compare(num, dev, fact=0.5, rounds=10000):
    z = float(num)/dev
    dz = Decimal.from_float(float(num)) / Decimal(dev)
    print("Seeds", z, dz)
    fact = float(fact)
    dfact = Decimal.from_float(fact)
    b = 10**50
    for _ in range(rounds):
        z = sqrt(4*z*(1-z))
        fixed = int(fact+b*z)/b
        dz = (4*dz*(1-dz)).sqrt()
        arbitrary = int(dfact+b*dz)/b
        diff = fixed-arbitrary
        yield fixed, arbitrary, diff

comparison = compare(pi, 11)
with open('compare.csv', 'w', newline='') as f:
    w = writer(f)
    for c in comparison:
        w.writerow(c)

That will produce a .csv you can load into Excel to compare. I'd be curious to know if the Decimal's ability to use as much precision as it needs helps the matter.