[Haskell-beginners] how to print a floating-point number?

Adrian Neumann aneumann at inf.fu-berlin.de
Thu Jan 8 13:22:34 EST 2009


Unlike other languages Haskell doesn't automatically convert  
numbertypes.

getCPUTime returns an Integer, which can't be divided with / (you'd  
have to use "div" for integer-division). However you can explicitly  
convert an Integer (or any Integral type, Ints too) with "fromIntegral".

>        print (fromIntegral time / 1.0e12)

should work. For more information refer to the haskell-wiki

 > http://haskell.org/haskellwiki/Converting_numbers


Am 08.01.2009 um 17:45 schrieb Sergei Winitzki:

> Subject: how to print a floating-point number?
> hi,
>
> I am very new to Haskell. I am trying to benchmark the CPU time needed
> for a computation, and I can't figure out how to print a
> floating-point number.
>
> My code is as follows, and I expected it to work:
>
> import System.CPUTime
> main = do
>        let result = some_computation
>        print result
>        time <- getCPUTime          -- this is an Integer that needs
> to be divided by 1e12 to get time in seconds
>        print (time / 1.0e12)           -- I want this to print a
> floating-point number
>
>
> But this does not compile.
> Error message:    No instance for (Fractional Integer)
>      arising from use of `/' at fact1.hs:18:15-28
>    Possible fix: add an instance declaration for (Fractional Integer)
>    In the first argument of `print', namely `(time1 / 1.0e12)'
>
>  I thought this should work because e.g. 12 / 7 evaluates to
> 1.7142857142857142 in ghci.
> I understand this is some problem with types, but surely it is fixed
> not by adding any instance declarations but perhaps by using some
> Prelude or Numeric function. But which one?
>  I tried everything I could find in the documentation: showFloat,
> adding ::Float everywhere, adding fromIntegral, etc.etc. - nothing
> works. All the books and the tutorials I looked at seem to discuss at
> length such nice things as Fibonacci numbers and recursive factorial
> functions rather than a practical problem like this.
>
> help will be much appreciated!
>
> Sergei
> _______________________________________________
> Beginners mailing list
> Beginners at haskell.org
> http://www.haskell.org/mailman/listinfo/beginners

-------------- next part --------------
A non-text attachment was scrubbed...
Name: PGP.sig
Type: application/pgp-signature
Size: 194 bytes
Desc: Signierter Teil der Nachricht
Url : http://www.haskell.org/pipermail/beginners/attachments/20090108/ac5423b9/PGP.bin


More information about the Beginners mailing list