java - Java中如何防止四舍五入到零

标签 java floating-point processing

我正在制作一个模拟此视频中显示的风车动画的处理草图:3Blue1Brown Windmill Problem然而,我遇到了一个问题,我的浮点值在不应该的情况下被舍入为零。例如,我可以使用以下行: float ratio= (520-581)/(158-87)这应该给出 -0.859 的结果,但它只给出 0.0。我知道由于 float 的工作原理, float 通常会存在一定程度的不准确性,但这似乎很极端。我做错了什么,该如何解决?

以下是感兴趣的人的完整代码片段:

void detectCollision(ArrayList<Point> points){
for(Point point : points){
  int x1 = rotationalPoint[0];
  int y1 = rotationalPoint[1];
  int x2 = point.get()[0];
  int y2 = point.get()[1];

  //skips the point if it's the same as the pivot point
  if(x2 != x1 && y2 != y1){
    //calculate the angle from the pivot point to a given point
    float theta = atan((y2-y1)/(x2-x1));

    println("Theta Before: " + degrees(theta));
    /* These two lines compensate for the fact that atan as a range from PI/2 to -PI/2
    they give the atan function a range from 0 to 2PI
    */
    if(x2-x1 < 0) theta += PI;
    if(x2-x1 > 0 && y2-y1 < 0) theta = 2*PI-abs(theta);

    //some lines to help debug
    println("P1: " + x1 + ", " + y1 + " P2: " + x2 + ", " + y2);
    println("Theta: " + degrees(theta) + " Angle: " + degrees(angle));

    /*checks to see if the current line's angle is close  to the angle from the pivot point to the given point
    if it is then it will make the given point the new pivot point
    */
    if(angle<theta+rotationRate/2 && angle > theta-rotationRate/2){
      this.rotationalPoint[0] = x2;
      this.rotationalPoint[1] = y2;
    }
  }
}
}

感谢您的帮助!

最佳答案

除法将整数值作为参数,因此,它执行不带浮点的“整数除法”。 在进行除法之前将您的值解析为 float:

float ratio = (float)(520-581) / (float)(158-87);
System.out.println(ratio);

-0.85915494

祝你好运!

关于java - Java中如何防止四舍五入到零,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58037028/

相关文章:

java - 使用动态规划计算多个值的箱子中有多少球

java - PowerMockito 测试遗留代码

C++ 浮点算术运算

javascript - 如何使用 Google 自定义搜索 API 下载 100 张图像以用于处理?

java - 当 "X px"仅被按下一次时使 block /角色移动 "W or w",并且当 "W and w"被按住时不继续行走

java - 如何将图像数据作为 base 64 字符串写入文本文件?

java - 使用它的客户端 API 解析深度嵌套的 elasticsearch 聚合

c# - 如何在 C# 中将 Decimal 转换为 Double?

python - 分数背后的重要原因(0.1) = 3602879701896397/36028797018963968

javascript - p5.j​​s 中的 3d 数组移动?