在Ruby中比较两个浮点数,结果为false。

huangapple go评论49阅读模式
英文:

comparing two floating numbers in Ruby, giving false

问题

我有两个数字:
balance1 = 0.253164557e-4(将给出0.0000253164557)
balance2 = 0.00002531

现在,当我在Ruby中进行比较时:
balance1 == balance2,由于精度问题,它返回false。

但是,我的要求是将它们视为相等,请提出方法来实现这一点。

英文:

I have two numbers:
balance1 = 0.253164557e-4 (which would give 0.0000253164557)
balance2 = 0.00002531

now when I compare then in ruby like:
balance1 == balance2 , it gives false due to precision issue

but my requirement consider them to be equal, suggest ways to do this

答案1

得分: 2

浮点数不适用于精确比较。通常,本应相等的两个数字实际上略有不同。比较两个浮点数的一种方法是使用一个增量值。您可以检查两个数字之间的绝对差是否小于或等于增量值。例如:(期望浮点数 - 实际浮点数)。abs <= delta

英文:

Floating-point numbers are not suitable for exact comparison. Often, two numbers that should be equal are actually slightly different. One way to compare two floating-point numbers is by using a delta value. You can check if the absolute difference between the two numbers is less than or equal to the delta value. For example: (expected_float - actual_float).abs <= delta

huangapple
  • 本文由 发表于 2023年6月26日 16:58:13
  • 转载请务必保留本文链接:https://go.coder-hub.com/76555124.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定