I have problem with java maths. I have following expression:
double tripp = (timeNow-previousTime)/(seconds*Sys.getTimerResolution())*trip;
Where I am trying to calculate rotating speed of my cube. Here is my full code of that function here I do that:
public float getTripLenghtToGo(int seconds, double trip) {
long timeNow = Sys.getTime();
System.out.println("RES: "+Sys.getTimerResolution());
double tripp = (timeNow-previousTime)/(seconds*Sys.getTimerResolution())*trip;
System.out.println("("+timeNow+"-"+previousTime+")/("+seconds+"*"+Sys.getTimerResolution()+")*"+trip+" = "+tripp);
if(tripp != 0){
previousTime = timeNow;
}
return (float)tripp;
}
I use OpenGL so it must return float. It returns float, but always zero.
timeNow
is long
type. The "upper" part of your division gives a long. The whole division will give a long. You need to cast it to double, or the decimal part will be lost.
For example, the output of:
long timeNow = 10;
long previousTime = 1;
double trip = 0.1d;
int seconds = 50;
double trippCast = ((double) (timeNow-previousTime))/((double)seconds)*trip;
System.out.println(trippCast);
double trippWithoutCast = (timeNow-previousTime)/seconds*trip;
System.out.println(trippWithoutCast);
is:
0.018
0.0
Two possibilities:
System.nanoTime()
- it gives you more precise time measurement ((double)(timeNow-previousTime))/(seconds*Sys.getTimerResolution())
- if you divide a long with int, the result will be long. And that's 0L
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.