简体   繁体   English

java用浮点数和双打计算

[英]java calculating with floats and doubles

I have problem with java maths. 我有java数学的问题。 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. 我使用OpenGL所以它必须返回float。 It returns float, but always zero. 它返回float,但始终为零。

timeNow is long type. timeNowlong型。 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. 您需要将其强制转换为double,否则小数部分将丢失。

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: 两种可能性:

  • Use System.nanoTime() - it gives you more precise time measurement 使用System.nanoTime() - 它可以为您提供更精确的时间测量
  • use ((double)(timeNow-previousTime))/(seconds*Sys.getTimerResolution()) - if you divide a long with int, the result will be long. use ((double)(timeNow-previousTime))/(seconds*Sys.getTimerResolution()) - 如果用long除以long,结果将为long。 And that's 0L 那是0L

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM