I made a program to count infinite sum of series but get an error: stack overflow. Help please
let sum_series (max : float) =
let rec f (a:float, x : float) =
match x with
| 0. -> a
| x -> f ((1. / (x * x) + a), x - 1.)
f (0., max)
[<EntryPoint>]
let main args =
let (b, max) = System.Double.TryParse(args.[0])
printfn "%A" (sum_series max)
0
The code gets into an infinite loop if you call the function with a max
value that is not an integer. The issue is that you keep subtracting 1.0
from max
in each step, but then you only check whether it equals 0.0
at the end. If you start with 0.1
, your next values will be -0.9, -1.9, -2.9
etc.
Do you just want to check for a case when x
is less then 0.0
? You can change your match
to an ordinary if
(which makes this simpler) and use:
let sum_series (max : float) =
let rec f (a:float, x : float) =
if x < 0. then a
else f ((1. / (x * x) + a), x - 1.)
f (0., max)