How can I convert integer into float in Java? - java

I have two integers x and y. I need to calculate x/y and as outcome I would like to get float. For example as an outcome of 3/2 I would like to have 1.5. I thought that easiest (or the only) way to do it is to convert x and y into float type. Unfortunately, I cannot find an easy way to do it. Could you please help me with that?

You just need to cast at least one of the operands to a float:
float z = (float) x / y;
or
float z = x / (float) y;
or (unnecessary)
float z = (float) x / (float) y;

// The integer I want to convert
int myInt = 100;
// Casting of integer to float
float newFloat = (float) myInt

You shouldn't use float unless you have to. In 99% of cases, double is a better choice.
int x = 1111111111;
int y = 10000;
float f = (float) x / y;
double d = (double) x / y;
System.out.println("f= "+f);
System.out.println("d= "+d);
prints
f= 111111.12
d= 111111.1111
Following #Matt's comment.
float has very little precision (6-7 digits) and shows significant rounding error fairly easily. double has another 9 digits of accuracy. The cost of using double instead of float is notional in 99% of cases however the cost of a subtle bug due to rounding error is much higher. For this reason, many developers recommend not using floating point at all and strongly recommend BigDecimal.
However I find that double can be used in most cases provided sensible rounding is used.
In this case, int x has 32-bit precision whereas float has a 24-bit precision, even dividing by 1 could have a rounding error. double on the other hand has 53-bit of precision which is more than enough to get a reasonably accurate result.

You just need to transfer the first value to float, before it gets involved in further computations:
float z = x * 1.0 / y;

Here is how you can do it :
public static void main(String[] args) {
// TODO Auto-generated method stub
int x = 3;
int y = 2;
Float fX = new Float(x);
float res = fX.floatValue()/y;
System.out.println("res = "+res);
}
See you !

Sameer:
float l = new Float(x/y)
will not work, as it will compute integer division of x and y first, then construct a float from it.
float result = (float) x / (float) y;
Is semantically the best candidate.

Related

Why does my float type-casting expression return two different values?

Here are the expressions I'm working with:
float firstValue = (float) (5 / 2); //output is 2.0
float secondValue = (float) 5 / 2; //output is 2.5
I'm stumped here and can't figure out why this type casting is returning two different values. I understand I can just do (5f / 2f) but I wanted to experiment using the other type casting with an expression. Why is firstValue 2.0 and secondValue 2.5? Where did the .5 go?
As brackets have the highest precedence, they get solved first
float firstValue = (float) (5 / 2); // division of integers
= (float) (2); // 5/2 = 2 , as Integers are being divided
= 2f
float secondValue = (float) 5 / 2; // division of float with integer
= ((float) 5) / 2;
= 5f / 2; // second value is equivalent to this
= 2.5f // as Float divided by Integer is Float
The first is integer math. This
float firstValue = (float) (5 / 2);
First divides five by two and gets two. Then it converts two to 2.0. The second is floating point math.
float secondValue = 5f / 2;
Which is 2.5 (and a float). Because a float divided by an int is a float.
float firstValue = (float) (5 / 2); // division of integers
The first step is to do 5/2 calculation.Then the answer is given in float.If you explain further 5 and 2 are int numbers. After calculating the int for two int numbers, the final answer is returned by int. Here the final int answer (2) is converted to a float answer. That is, wider conversion is used here. So the final answer is the integer value(2) shown in float form(2.0).
2.float secondValue = (float) 5 / 2; //output is 2.5
Since the first value(5) is named a float number, the final answer is the decimal itself

Java performance optimization

For a JOGL game I get very low fps, now with some testing I found out the problem is not in the JOGL part, but in pure Java calculations. I need to define a lot of float variables, which takes up 90% of the time.
I have tested for 45 float variables, where only 16 get an initial value. The rest is just float z1; float z2;, etc. This took around 5-10 milliseconds, according to System.currentTimeMillis().
But this code with the 45 floats is in a method called by a double loop. In total this method is called 49 times (7*7). All this is inside the JOGL method to draw the game in a JFrame, but because of this many float variables it takes a total of 100ms, which means only 10fps.
So basically the problem is that I have to initialize 45*49=2205 floats. Is there any way to optimize this to get a better fps?
For example, would a double be faster than a float? Or would it help to define the variables first outside the loop, and give them their value inside the loop? Does anyone know a way to make this code run faster? Thanks a lot in advance.
EDIT
As requested, here is the source code:
for (int x = -4; x < 3; x++) { // Loops 7 times
for (int y = -4; y < 3; y++) { // Loops 7 times
long t1 = System.currentTimeMillis();
float z0 = terrain.getHeight(x-1, y-1); // Simple method, but takes up about half of the time
float z1 = terrain.getHeight(x , y-1);
float z3 = terrain.getHeight(x+1, y-1);
float z4 = terrain.getHeight(x+2, y-1);
float z5 = terrain.getHeight(x-1, y );
float z6 = terrain.getHeight(x , y );
float z7;
float z8;
float z9;
float z10 = terrain.getHeight(x+1, y );
float z11 = terrain.getHeight(x+2, y );
float z12;
float z13;
float z14;
float z15;
float z16;
float z17;
float z18;
float z19;
float z20;
float z21;
float z22;
float z23;
float z24;
float z25;
float z26;
float z27;
float z28;
float z29;
float z30;
float z31;
float z32;
float z33 = terrain.getHeight(x-1, y+1);
float z34 = terrain.getHeight(x , y+1);
float z35;
float z36;
float z37;
float z38 = terrain.getHeight(x+1, y+1);
float z39 = terrain.getHeight(x+2, y+1);
float z40 = terrain.getHeight(x-1, y+2);
float z41 = terrain.getHeight(x , y+2);
float z43 = terrain.getHeight(x+1, y+2);
float z44 = terrain.getHeight(x+2, y+2);
t1 = System.currentTimeMillis() - t1;
// Some other code where I use these variables.
// Takes between 0-1 ms in total.
}
}
EDIT
I now tested the getHeight() method, and it takes up about half of the time. The seven variables which use this method add up to about 5 ms, where the total is 10. The following is the code used in getHeight():
public float getHeight(float x, float y) {
long t1 = System.currentTimeMillis();
Coordinate c = new Coordinate(x, y);
for (Entry<Coordinate, Float> e : heightMap.entrySet()) { // heightMap = HashMap<Coordinate, Float>
if (e.getKey().x == c.x && e.getKey().y == c.y) {
System.out.println("getHeight: " + (System.currentTimeMillis() - t1) + " ms");
return e.getValue();
}
}
return 0f;
}
Coordinate is a class I made myself, it has a constructor with two float parameters for x and y, and saves them public, globally in the class itself.
The reason why I am not using heightMap.get(c), is because this always throws a NullPointerException, while the code given above never reaches the last line of return 0f;.
EDIT
Found the solution to the problem in this [link] (Why are custom objects not equivalent keys for a HashMap?) question, namely that I had to add public boolean equals(Object other) and public int hashCode() to my custom Coordinate class. Now the getHeight method can work with heightMap.get(c), which removes the loop in there and makes the program a lot faster. The total (with 49 loops) takes around 1 ms now.
Please note that Full Screen Exclusive Mode must be used for some operating systems to give you enough resources.
Defining variables outside of the loop will not help, as Java optimizes your code and defining variables inside a loop actually gives Java hints to increase performance. What I think (and I can only guess, since you posted no code) is, that you may consider using an array of longs. They are very effective to work with in a loop and they're also allocated one after another in your memory, so cache can be used effectively.
To me, fillings 2025 Longs takes slightly above one millisecond, including calls to random.nextLong() method.
public Long fillLongs(int numberofLongs) {
long[] longs = new long[numberofLongs];
Random r = new Random();
long start = System.currentTimeMillis();
for (long l : longs) {
l = r.nextLong();
}
long end = System.currentTimeMillis();
return end - start;
}
Using parallel stream, this task takes even less time. Often under 1 ms.
public Long fillLongs(int numberofLongs) {
Long[] longs = new Long[numberofLongs];
List<Long> longList = Arrays.asList(longs);
Random r = new Random();
long start = System.currentTimeMillis();
longList.parallelStream().forEach(l -> {
l = r.nextLong();
});
long end = System.currentTimeMillis();
return end - start;
}
For high-performance computing in Java you might consider usi JNI (Java Native Interface) - though it requires C++ knowledge. For a quick start take a look here.

Rotation - lack of precision - Java

I hava a class representing a point (x and y coordinates are double type) and a function to rotate the point around another point:
public Point2D rotate(double angle, Point2D origin) {
double sin = Math.sin(angle);
double cos = Math.cos(angle);
x -= origin.getX();
y -= origin.getY();
x = x*cos - y*sin;
y = x*sin + y*cos;
x += origin.getX();
y += origin.getY();
return this;
}
However when I repeat the rotation many times (i.e. by 1 Degree) I loose much of precision. Example:
Point2D point = new Point2D(10, 10);
System.out.println(point);
for(int i = 0; i < 360; i++)
point.rotate(Math.toRadians(1), new Point2D(300, 150));
System.out.println(point);
And the results:
[10.0, 10.0]
[25.5048671135757, 17.40466547204096]
Do you have any idea how to solve this issue? Thanks in advance.
firstly, there's an error in your formula...
the line
x = x*cos - y*sin;
modifies the value of x and the modified value is used in the next line
y = x*sin + y*cos;
You have to use a temp variable to store the new value of x and y, this is what user2602548 meant with his sugestion.
I guess you're already using double since you would otherwise need a cast to float for those two lines.
If you fix the algorithmic error you get something like [9.99999999999659, 9.999999999998778] .
If that's not good enough for you, you could either round after the rotations and if that's also not good enough use a lib that provides trigonometric functions with more precision like apfloat.
Using BigDecimal with that problem won't give you any more precision because the problem here is that the results of sin() and cos() are still only double precision.

How to implement the "fast inverse square root" in Java?

I've heard of the "fast inverse square root", discussed here, and I wanted to put it in my Java program (just for research purposes, so ignore anything about the native libraries being faster).
I was looking at the code, and the C code directly converts the float into an int with some C pointer magic. If you try to do this in Java with casts, it doesn't work: java truncates the float (as you would expect), and you can't get the pointer of a primitive (as you can in C).
So how do you do this?
Remember to benchmark your code before using this.
If it turns out you don't need it, or it's slower on the CPU architecture you are using, then it's better to go without having this obtuse code in your project.
The Java libraries have a way to get from the float number to the raw bits.
As seen in the Javadoc for java.lang.Float ( http://docs.oracle.com/javase/6/docs/api/java/lang/Float.html ), we have the floatToIntBits function, as well as intBitsToFloat.
This means we can write the "fast inverse square root" in Java as follows:
public static float invSqrt(float x) {
float xhalf = 0.5f * x;
int i = Float.floatToIntBits(x);
i = 0x5f3759df - (i >> 1);
x = Float.intBitsToFloat(i);
x *= (1.5f - xhalf * x * x);
return x;
}
Here is the version for doubles:
public static double invSqrt(double x) {
double xhalf = 0.5d * x;
long i = Double.doubleToLongBits(x);
i = 0x5fe6ec85e7de30daL - (i >> 1);
x = Double.longBitsToDouble(i);
x *= (1.5d - xhalf * x * x);
return x;
}
Source: http://www.actionscript.org/forums/showthread.php3?t=142537
For Riking's answer, even the double one can return stuff like 0.9983227945440889 for the square root of one.
To increase accuracy, you can use this version of it I made:
public static double Q_rsqrt(double number){
double x = number;
double xhalf = 0.5d*x;
long i = Double.doubleToLongBits(x);
i = 0x5fe6ec85e7de30daL - (i>>1);
x = Double.longBitsToDouble(i);
for(int it = 0; it < 4; it++){
x = x*(1.5d - xhalf*x*x);
}
x *= number;
return x;
}
You can edit how long before the for loop terminates however you want, but 4 times seems to get it down to the maxiumum accuracy for a double. If you want perfect accuracy (or if long strings of decimals where they shouldnt be bother you), use this version.

percentage of two int?

I want to get two ints, one divided by the other to get a decimal or percentage.
How can I get a percentage or decimal of these two ints?
(I'm not sure if it is right.. I'm probably way off...)
for example:
int correct = 25;
int questionNum = 100;
float percent = correct/questionNum *100;
This is how I thought I could do it, but it didn't work... I want to make the decimal (if there is one) into a percent out of 100 for example in this case it is %25. any ideas anyone?
Here is the correct code (thanks to Salvatore Previti!):
float correct = 25;
float questionNum = 100;
float percent = (correct * 100.0f) / questionNum;
(btw, I am making a project using this for a quiz checking program that is why I need the percentage or decimal)
If you don't add .0f it will be treated like it is an integer, and an integer division is a lot different from a floating point division indeed :)
float percent = (n * 100.0f) / v;
If you need an integer out of this you can of course cast the float or the double again in integer.
int percent = (int)((n * 100.0f) / v);
If you know your n value is less than 21474836 (that is (2 ^ 31 / 100)), you can do all using integer operations.
int percent = (n * 100) / v;
If you get NaN is because wathever you do you cannot divide for zero of course... it doesn't make sense.
Two options:
Do the division after the multiplication:
int n = 25;
int v = 100;
int percent = n * 100 / v;
Convert an int to a float before dividing
int n = 25;
int v = 100;
float percent = n * 100f / v;
//Or:
// float percent = (float) n * 100 / v;
// float percent = n * 100 / (float) v;
One of them has to be a float going in. One possible way of ensuring that is:
float percent = (float) n/v * 100;
Otherwise, you're doing integer division, which truncates the numbers. Also, you should be using double unless there's a good reason for the float.
The next issue you'll run into is that some of your percentages might look like 24.9999999999999% instead of 25%. This is due to precision loss in floating point representation. You'll have to decide how to deal with that, too. Options include a DecimalFormat to "fix" the formatting or BigDecimal to represent exact values.
float percent = (n / (v * 1.0f)) *100

Categories