【问题标题】:How to get around a Possible Loss of Precision Error in java如何解决java中可能的精度损失错误
【发布时间】:2015-06-15 23:08:30
【问题描述】:

我正在开发一个缩放系统,将数字缩放 25% 并四舍五入到最接近的整数,为此,我试图通过将 double 转换为 int 来依靠精度损失。有没有办法解决这个问题?还是我应该以不同的方式去做?

public int[] scaleMarks(int[] marks)
{
    double scale = 1.25;
    double temp1;
    int temp2;

    for(int i = 0; i < marks.length; i++)
    {
        temp1 = marks[i] * scale;
        temp2 = marks[i] * scale; //***Loss of precision here***

        if(temp1-temp2>= 0.5)
        {
            temp2++;
        }
        marks[i] = temp2;

    }


    return marks;
}

【问题讨论】:

  • “试图依靠精度损失”.....这似乎很危险。
  • 将 double 转换为 int 不会四舍五入到最近的 int,而是将其取整。
  • 好吧,我知道它会成为低于实际值的最接近的整数,我打算使用两者之间的差异来确定我应该采用哪种方式舍入,但我想我刚刚解决了.通过使其 temp2 = (int) (marks[i] * scale);它似乎可以编译,但我目前无法对其进行测试,因为我的笔记本电脑不允许我运行编译后的文件。
  • 将其设为 temp2 = (int) (marks[i] * scale) 只是将小数点直接向上。
  • 然后我在 if 语句中检查它们之间的差异以建立舍入。

标签: java scaling


【解决方案1】:

您需要使用Math.round 对产品进行四舍五入,以便可以安全地将其转换为int

marks[i] = (int) Math.round(marks[i] * scale);

【讨论】:

  • 这看起来会大大缩短我的代码。有机会我一定会测试的。
【解决方案2】:

如果您想要取整而不是截断,则需要使用 Math.round。

public class Test {
  public static void main(String[] args) {
    System.out.println((int)0.999999);
    System.out.println(Math.round(0.999999));
  }
}

输出

0
1

【讨论】:

    【解决方案3】:

    你可以使用 Math.round 函数来避免它:

    (int)Math.round(marks[i] * scale);
    

    编辑:您必须将其转换为int,因为如果您不这样做,结果将是错误的(因为scale 它是double)。

    希望对你有所帮助!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-07-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多