gpt4 book ai didi

java - 我如何比较两个 double 的相等性?

转载 作者:行者123 更新时间:2023-11-30 03:11:31 26 4
gpt4 key购买 nike

在我的代码中:

else if (returnShortestTime() == shortTime[1])

returnShortestTime 方法返回最小的 double ,并与存储的 double 进行比较,所以因为这并不简单地使用 double A == double B 我如何比较代码中的两个 double 以查看它们是否相等?

最佳答案

一般而言,实际上您可以在 Java 中使用 == 来表示原始数据类型。比较 float 是否相等通常不是一个好主意的原因是 floating point precision error 。比较两个 float ( double )的相等性有两种解决方案,您可以使用 Java 的 BigDecimal 或检查两个数字之间的差异是否小于某个阈值(这通常称为 Epsilon value )。

使用BigDecimal

BigDecimal foo = new BigDecimal(returnShortestTimeAsString() /*String Representation of your returnShortestTime() method*/);
BigDecimal bar = new BigDecimal(shortTimeAsString[1] /*String Representation of this array value*/);
if(foo.compareTo(bar) == 0 /*If they are equal*/) doStuff();

使用 Epsilon

if(Math.abs(returnShortestTime() - shortTime[1]) < Math.ulp(1.0) /*This is the Epsilon value*/) doStuff();

关于java - 我如何比较两个 double 的相等性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33541357/

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