Heron's method in haskell

Viewed 318

I'm getting divide by zero exceptions in this code of heron's method, and I am kind of lost here.

epsilon:: Integral a => a
epsilon = 1

heron:: Integral a => a -> a
heron r = help 0
  where
    help x
      | abs (heron' x - heron' (x + 1)) < epsilon = heron' (x + 1)
      | otherwise                                 = help (x + 1)

    heron' 0 = 1
    heron' x = (1 `div` 2) * (heron' (x-1) + (r `div` heron' (x-1)))

Any suggestions where in this code I have to look to solve this problem?

(1 `div` 2) is definitely a problem , but what do I need to write instead?

1 Answers

If you need division of this kind, you probably want to use (/) instead of div and Fractional instead of Integral. So:

epsilon:: Fractional a => a
epsilon = 1

heron:: (Fractional a, Ord a) => a -> a
heron r = help 0
  where
    help x
      | abs (heron' x - heron' (x + 1)) < epsilon = heron' (x + 1)
      | otherwise                                 = help (x + 1)

    heron' 0 = 1
    heron' x = (1 / 2) * (heron' (x-1) + (r / heron' (x-1)))
Related