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!?
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.
You can divide a floating point number with integer.
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.
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.
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 ;
n / 1024 is integer division, which yields an integer (ie. 0 in this case).
Use n / 1024.0
instead.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With