Numerical code, floating point divergence

Hi all;
What is wrong with the following code? It prints “Infinity” when I run it in the interactive interpreter.

let pi_approx =
    let rec sum n accum = if n = 0 then accum else sum (n - 1) (accum + (1. / (float (n * n))))
    6. * sum 80000 0.

printf "%f" pi_approx

I thought the tailcall annotation might help but it did not.

[<TailCall>]
let rec sum n accum = if n = 65535 then accum else sum (n - 1) (accum + (1. / (float (n * n))))

let pi_approx =
    sum 80000 0.
printf "%f" pi_approx

Nothing to do with recursion, apparently.

let pi_approx =
    let mutable sum = 0. 
    for i = 1 to 80000 do
        sum <- sum + (1. / float (i * i))
    done
    sum

printf "%f" pi_approx
// Infinity

Ah it’s because integers in F# are 32 bits by default. I see. Cool!

Even if the ints are changed to long ints, the resultant value is, unless I’m not reading it correctly, nowhere near the value of PI:

val pi_approx: float = 9.869529402

Is that what you are trying to do? Or is the actual result in this case irrelevant to the question?

1 Like

Hi @GarryP ,

Yes, that’s a silly typo that I didn’t bother to correct after I identified the divide by zero error, as I felt that a finite real number was a much superior approximation to pi than Infinity is :blush:

It is actually pi squared, not pi, the window to edit the original code has lapsed but the correct code should modify the last line to take the square root of the whole expression.

Ah, I see. That’s all good then. Thanks for clearing that up.