Harmonic number in F#:
let harmonicNumber n =
let harmonicSeed (current, next) =
Some(current, (next, 1.0m / (1.0m + (1.0m / next))))
match n > 0 with
| true -> Seq.reduce (+) (Seq.take n <| Seq.unfold harmonicSeed (1.0m, 1.0m / 2.0m))
| _ -> failwith "The argument should be a natural number."
> harmonicNumber 1;;
val it : decimal = 1.0M
> harmonicNumber 2;;
val it : decimal = 1.5M
> harmonicNumber 10;;
val it : decimal = 2.9289682539682539682539682540M
> harmonicNumber 100;;
val it : decimal = 5.1873775176396202608051176738M
> harmonicNumber 1000;;
val it : decimal = 7.4854708605503449126565180835M
> harmonicNumber 10000;;
val it : decimal = 9.787606036044382264178479457M
> harmonicNumber 100000;;
val it : decimal = 12.090146129863427947363117950M
> harmonicNumber 1000000;;
val it : decimal = 14.392726722865723631388218824M
No comments:
Post a Comment