gpt4 book ai didi

java - Java中如何处理精确精度?

转载 作者:太空宇宙 更新时间:2023-11-04 09:57:43 25 4
gpt4 key购买 nike

要求是检查二维平面上的特定点是否通过特定线。

给出的 2 个首字母点是 (3,1)(12, 3) 。直线的斜率可以计算为

(y2-y1) / (x2-x1)

然后可以用 y = mx + c 构建直线方程其中 m 是斜率,c 是常数。表示该线的方程为 2x + 3 = 9y

因此,要检查上面的线是否经过坐标(-6, -1) ,我们简单地检查 2x + 3 = 9y

2x + 3 = 2(-6) + 3 = -12 + 3 = -9 = 9(-1) -> true

使用笔和纸时这很容易。

但是,当斜率计算为 (3-1)/(12-3) = 2/9 时,java 中的精度就会丢失

使用 Bigdecimal,在计算斜率时出现异常

java.lang.ArithmeticException: Non-terminating decimal expansion; no exact representable decimal result.

还有双

    double slope = (double)(3-1)/(double)(12-3);  //0.2222222222222222
// Putting (3,1) to get c
double c = (double)(1) - (double)(slope * 3); //0.33333333333333337
Hence the equation of the line is y = 0.2222222222222222(x) + 0.33333333333333337

// to check whether (-6, -1) passes through the above line, put the x coordinate
double yCoordinate = 0.2222222222222222* (-6) + 0.33333333333333337;

y坐标为-0.9999999999999999这不是 -1 。所以结果是假的,但通过简单的数学计算得出的答案是正确的。如何才能得到预期的结果?

最佳答案

这足够接近给出精确值,但不是正确的方法

public double getExactValueDiv(double a,double b){
double tmp = a/b;
tmp=Math.round(tmp*1000000000)/1000000000
return tmp;
}

关于java - Java中如何处理精确精度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53897064/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com