本文介绍了关于实数不精确的偏执狂的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 29岁程序员,3月因学历无情被辞! 你好, 由于计算机必须以有限的字节集存储真实的 数字这一事实,因此会产生问题。可能存储的 十进制值的一个小的不精确。我不知道,dotnet框架 如何存储双倍,但是可以肯定的是,如果我在一些 实变量中存储1.234567,那么存储在内存中就像接近 1.2345670000000000000003454786544或 1.23456699999999999999999999999999999924354324。 由于此问题,有时可能会导致一些意外 比较if中的实数时的结果声明。 一些编程语言有内置保护,只比较 有限的位数(小于声明的类型的能力),当 要求比较两个实数,因此较小的十进制 字段中的垃圾不会引起注意。我一直在使用ApproximatelyEqual。方法,比较两个实数并提供精度:输入:A,B,精度 输出:(abs (AB)< = 10 ^( - 精度)) 示例: A = 1.00000000000001 B = 1.00000000000007 precision = 13 abs(AB)= 0.00000000000006 10 ^( - 精度)= 0.0000000000001 abs( AB)< = 10 ^( - 精度)=真 精度= 14 10 ^( - 精度)= 0.00000000000001 abs(AB)< = 10 ^( - precision)= false 对于我正在进行的项目,其中有多个操作使用 实数,我想确定,哪里有一些陷阱我可能会陷入其中。 比较没有自定义的实数数字是否安全ApproximatelyEqual 方法? 谢谢, Pavils 解决方案 Hallo,It is know issue that due to the fact that computer has to store the realnumbers in limited set of bytes, thus causing a minor imprecision from thedecimal value that likely was stored. I don''t know, how dotnet frameworkstored doubles, but it''s certain, that if I store, say, 1.234567 in somereal variable, it is stored in memory like something close to1.2345670000000000000003454786544 or1.234566999999999999999999999999999924354324.Due to this problem it may sometimes cause some unexpected results whencomparing the real numbers in "if" statement.Some programming languages have built-in protection, that compares onlylimited number of digits (less than declared capability of the type), whenasked to compare two real numbers, thus the garbage in the lesser decimalfields goes unnoticed. I have been using an "ApproximatelyEqual" method, forcomparing two real numbers and providing precision:input: A, B, precisionoutput: (abs(A-B) <= 10^(-precision))Example:A = 1.00000000000001B = 1.00000000000007precision = 13abs(A-B) = 0.0000000000000610^(-precision) = 0.0000000000001abs(A-B) <= 10^(-precision) = trueprecision = 1410^(-precision) = 0.00000000000001abs(A-B) <= 10^(-precision) = falseFor a project I am working on, where there are done multiple operations withreal numbers, I wanted to be sure, where there are some traps I may fall in.Is it safe to compare the real numbers without custom "ApproximatelyEqual"method?Thanks,Pavils 解决方案 这篇关于关于实数不精确的偏执狂的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云! 08-22 17:04