kkh
kkh

Reputation: 4869

Java assignment of integers to float

I have integers X Y and Z

I have this formula in which I am using to populate a float[][] array

The formula is x/(y*(x+z) in which all 3 are integers

But when calculated the value is 0, which is definitely not as I checked the values of x y and z.

How do I go about preventing this and showing the float value instead?

Many thanks in advance

Upvotes: 0

Views: 98

Answers (3)

Usman Salihin
Usman Salihin

Reputation: 281

Try this:

float a = x / (1.F * y * (x + z));

Upvotes: 0

Stephen C
Stephen C

Reputation: 718788

I assume that you are doing something like this:

floats[i][j] =  x / (y * (x + z));

The problem is that the calculation on the RHS is done using integer arithmetic ... because all of the values are integers. In particular, the division is an integer division, and that means that (for example) if 0 <= x < (y * (x + z), then the expression will most evaluate to zero.

The solution is to force the division to be performed using floating point arithmetic.

The second aspect of the problem is that there is a risk of integer overflow. In particular, the y * (x + z) sub-expression could overflow if one or more of the inputs is too large. That would result in a wildly incorrect value for that part of the calculation.

The solution to the overflow problem is to force the entire calculation to be done in floating point ... not just the final division; e.g.

floats[i][j] =  x / (y * ((float) x + z));

Finally, if you want the result to be accurate (or as accurate as possible) you should probably be using double instead of float. The problem with float is that it only represents numbers with a maximum of 24 bits of precision. That is roughly 7 decimal digits. Unless performance or storage is critical, double is preferred because it gives you 53 bits of precision. That is roughly 14 decimal digits.

Upvotes: 0

Denys S&#233;guret
Denys S&#233;guret

Reputation: 382132

You have to cast the integers (or just the fist one) to float :

float result = ((float)x)/(y*(x+z));

This will make the / operator produce a float from the operation.

Don't forget to check you're not dividing by zero.

Upvotes: 2

Related Questions