0

I am trying to make a simple code to get an aproximation for PI using haskell. However it seems the program predicts the result of the division is an Integer, even though the division is never exact (again, it is PI).... Or at least that is what I understand :P

Here is the code:

divpi :: Integer -> Double
divpi k = (((fatc (6*k)) * ((545140134*k) + 13591409))/((fatc (3*k)) * (pot (fatc k) 3) * (pot (-262537412640768000) k)))

fatc is factorial (fatc number) and pot is integer exponentiation (pot base exponent)

The error message:

ERROR file:.\haskel.hs:33 - Type error in explicitly typed binding
*** Term           : divpi
*** Type           : Integer -> Integer
*** Does not match : Integer -> Double

If necessary, here is the entire code

  • Whcih compiler/environment do you use? It does not looks like gch's error messages – max630 Mar 23 '18 at 00:28
  • https://wiki.haskell.org/Converting_numbers tldr: (1) type must be converted explicitely, (2) division is not defined for integers at all, convert them first – max630 Mar 23 '18 at 00:31

1 Answers1

1

In Haskell, / works on Fractional types. Yet your fatc and pot return integers. Haskell, unlike C, will never implicitly convert between any types, so we need to use fromInteger to get non-integer values out of it.

divpi :: Integer -> Double
divpi k = (fromInteger ((fatc (6*k)) * ((545140134*k) + 13591409)) / fromInteger ((fatc (3*k)) * (pot (fatc k) 3) * (pot (-262537412640768000) k)))

Also, as a future note, when you have complicated arithmetic like this, consider using where and let to create some intermediate variables. In addition to making things more readable, you'll get better error messages as well.

Silvio Mayolo
  • 62,821
  • 6
  • 74
  • 116