英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论