Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the right way to divide two Int values to obtain a Float?

I'd like to divide two Int values in Haskell and obtain the result as a Float. I tried doing it like this:

foo :: Int -> Int -> Float
foo a b = fromRational $ a % b

but GHC (version 6.12.1) tells me "Couldn't match expected type 'Integer' against inferred type 'Int'" regarding the a in the expression.

I understand why: the fromRational call requires (%) to produce a Ratio Integer, so the operands need to be of type Integer rather than Int. But the values I'm dividing are nowhere near the Int range limit, so using an arbitrary-precision bignum type seems like overkill.

What's the right way to do this? Should I just call toInteger on my operands, or is there a better approach (maybe one not involving (%) and ratios) that I don't know about?

like image 596
Wyzard Avatar asked Jul 18 '10 10:07

Wyzard


People also ask

How do you find the float value by dividing two integers?

Dividing an integer by an integer gives an integer result. 1/2 yields 0; assigning this result to a floating-point variable gives 0.0. To get a floating-point result, at least one of the operands must be a floating-point type. b = a / 350.0f; should give you the result you want.

How do you divide float values?

To divide float values in Python, use the / operator. The Division operator / takes two parameters and returns the float division. Float division produces a floating-point conjecture of the result of a division.

Why is int divided by int a float?

If one of the operands in you division is a float and the other one is a whole number ( int , long , etc), your result's gonna be floating-point. This means, this will be a floating-point division: if you divide 5 by 2, you get 2.5 as expected.

How do you find the float value after division?

Just use $value = (float)($x/$y); //Result will in float. Cheers!


1 Answers

You have to convert the operands to floats first and then divide, otherwise you'll perform an integer division (no decimal places).

Laconic solution (requires Data.Function)

foo = (/) `on` fromIntegral 

which is short for

foo a b = (fromIntegral a) / (fromIntegral b) 

with

foo :: Int -> Int -> Float 
like image 161
Dario Avatar answered Oct 21 '22 20:10

Dario