Swift中为何相等的Double值比较始终返回false?
解决Swift中Double比较始终返回false的问题
嘿,这个问题我太熟了——这完全是浮点数精度限制在搞鬼!
问题根源分析
先看你的代码:
let latestlogoValue = log(Double(125))/log(5.0) let latestlogIntValue:Int = Int(latestlogoValue) print(latestlogoValue) print(Double(latestlogIntValue)) print(Double(latestlogIntValue) == Double(latestlogoValue)) //Always returning false
理论上log₅(125)的结果是3,但因为Double是64位浮点数,它只能精确存储有限的数值,像log这类数学运算的结果往往是近似值,而非完美的整数。你仔细打印latestlogoValue的完整值,大概率会看到类似3.0000000000000004或者2.9999999999999996的结果,而不是精确的3.0。
当你把这个近似值转成Int时,Int会直接截断小数部分(比如3.0000000000000004转成3),再转回Double就是精确的3.0——一个是近似的3,一个是精确的3,用==比较自然会返回false。
解决方案
针对这个场景,有两种常用的处理方式:
1. 使用阈值(Epsilon)比较
不要直接用==判断浮点数相等,而是判断两个值的绝对差是否小于一个极小的阈值(通常用1e-9,这个值足够小,不会影响常规业务场景的判断):
let latestlogoValue = log(Double(125))/log(5.0) let latestlogIntValue: Int = Int(latestlogoValue) let epsilon = 1e-9 let isEqual = abs(Double(latestlogIntValue) - latestlogoValue) < epsilon print(isEqual) // 现在会返回true
2. 绕开浮点数,用整数运算解决
如果你本来的需求是判断125是否是5的整数次幂,完全可以不用浮点数运算,直接用整数逻辑验证,从根源避免精度问题:
func isPower(of base: Int, number: Int) -> Bool { guard number > 0, base > 1 else { return false } var num = number while num % base == 0 { num /= base } return num == 1 } print(isPower(of: 5, number: 125)) // 输出true
总结
浮点数的==比较一定要谨慎,它们的二进制存储特性决定了很多时候“逻辑上相等”的值,实际存储的是近似值。用阈值比较是处理这类问题的通用方案;如果是特定的数学场景,优先考虑整数运算,能避免很多不必要的精度坑。
内容的提问来源于stack exchange,提问作者RSP
相关产品推荐
相关产品推荐

