Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

recommended way to convert Double -> Float in Haskell

What is the idiomatic way to go Double -> Float?

Is it uncurry encodeFloat . decodeFloat ?

(I am using gloss, this requires Floats)

And what is the recommended way to find an answer to such questions?

I was trying this hoogle query but the answers are all very unhelpful (try it - it has unsafeCoerce at the top of the list)

like image 824
d8d0d65b3f7cf42 Avatar asked May 04 '15 11:05

d8d0d65b3f7cf42


People also ask

How do you convert to double in Haskell?

The usual way to convert an Int to a Double is to use fromIntegral , which has the type (Integral a, Num b) => a -> b . This means that it converts an Integral type ( Int and Integer ) to any numeric type b , of which Double is an instance.

Is it better to use double or float?

double is mostly used for calculations in programming to eliminate errors when decimal values are being rounded off. Although float can still be used, it should only be in cases when we're dealing with small decimal values. To be on the safe side, you should always use double .

Is float more efficient than double?

Floats are faster than doubles when you don't need double's precision and you are memory-bandwidth bound and your hardware doesn't carry a penalty on floats. They conserve memory-bandwidth because they occupy half the space per number. There are also platforms that can process more floats than doubles in parallel.

Can a float be converted to a double?

The doubleValue() method of Java Float class returns a double value corresponding to this Float Object by widening the primitive values or in simple words by directly converting it to double via doubleValue() method .


1 Answers

Use realToFrac :: (Real a, Fractional b) => a -> b.

It converts from any real number type (like Int, Float or Double) to any fractional type (like Float, Double or Rational).

Note that even though the general definition of this function (fromRational . toRational) does a slow conversion via the Rational type, there are rewrite rules which use more efficient implementations for conversions between Float and Double.

like image 85
hammar Avatar answered Nov 09 '22 19:11

hammar