Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does dividing a float by an integer return 0.0?

So if I have a range of numbers '0 - 1024' and I want to bring them into '0 - 255', the maths would dictate to divide the input by the maximum the input will be (1024 in this case) which will give me a number between 0.0 - 1.0. then multiply that by the destination range, (255).

Which is what I want to do!

But for some reason in Java (using Processing) It will always return a value of 0.

The code would be as simple as this

float scale; scale = (n/1024) * 255; 

But I just get 0.0. I've tried double and int. all to no avail. WHY!?

like image 315
Arif Driessen Avatar asked Sep 23 '10 14:09

Arif Driessen


People also ask

What happens if you divide float by INT?

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.

Can you divide a float by an int?

You can divide a floating point number with integer.

Can you divide a float?

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. If you are working with Python 3 and you need to perform a float division, then use the division operator.

Why does division return float?

The numeric arguments are first converted to a common type. Division of integers yields a float, while floor division of integers results in an integer; the result is that of mathematical division with the 'floor' function applied to the result. The result of flooring is safe to convert to an integer.


2 Answers

It's because you're doing integer division.

Divide by a double or a float, and it will work:

double scale = ( n / 1024.0 ) * 255 ; 

Or, if you want it as a float,

float scale = ( n / 1024.0f ) * 255 ; 
like image 81
tim_yates Avatar answered Oct 01 '22 20:10

tim_yates


n / 1024 is integer division, which yields an integer (ie. 0 in this case).

Use n / 1024.0 instead.

like image 27
Alexandre C. Avatar answered Oct 01 '22 20:10

Alexandre C.