gpt4 book ai didi

c# - 双重和舍入很难,但这太疯狂了

转载 作者:太空宇宙 更新时间:2023-11-03 17:25:02 25 4
gpt4 key购买 nike

double a = 135.24;          // a is set to 135.24000000000001 actually
double b = Math.Round(a, 0); // set to 135.0
double c = Math.Round(a, 1); // set to 135.19999999999999
double d = Math.Round(a, 2); // set to 135.24000000000001
double e = Math.Round(a, 3); // set to 135.24000000000001
double f = Math.Round(a, 4); // set to 135.24000000000001
double g = Math.Round(a, 5); // set to 135.24000000000001
double h = Math.Round(a, 10); // set to 135.24000000000001
double i = Math.Round(a, 14); // set to 135.24000000000001


double j = Math.Round(a, 2
, MidpointRounding.AwayFromZero ); // set to 135.24000000000001
double k = Math.Round(a, 2
, MidpointRounding.ToEven ); // set to 135.24000000000001

Sooooo,这意味着 135.24 不能用 double 表示,对吧?

最佳答案

是的,135.24 不能用 double 表示,因为 double 使用二进制指数表示法。

即:135.24 可以以 2 为底指数表示为 1.0565625 * 128 = ( 1 + 1/32 + 1/64 + 1/128 + 1/1024 + ... ) * (2**7) .

表示不能完全做到,因为13524不能除以5,我们看:

135.24 = 13524/(10**2)

representation is finite <=> exist whole x and n satisfying 135.24 = x/(2**n)

135.24 = x/(2**n)
13524 / (10**2) = x / (2**n)
13524 * (2**n) = (10**2) * x
13524 * (2**n) = 2*2*5*5 * x

there is no "5" on the left side, so it cannot be done (known as the Fundamental Theorem of Arithmetic)

一般来说,只有在十进制数的质因数分解中有足够多的“五”时,有限二进制表示才是准确的。

现在是有趣的部分:

    double delta = 0.5;
while( 1 + delta > 1 )
delta /= 2;

Console.WriteLine( delta );

double 的精度在 1 附近不同,在 0 附近不同,对于一些大数字也不同。维基百科上的一些二进制表示示例:Double precision floating point format

但最重要的是,内部处理器浮点堆栈可能比 8 字节( double )精度更高。如果不必将数字传输到 RAM 并将其剥离到 8 个字节,我们可以获得非常好的精度。

在不同的处理器(AMD、Intel)、语言(C、C++、C#、Java)或编译器优化级别上测试类似的东西可以得到大约 1e-16、1e-20 甚至 1e-320 的结果

查看 CIL/汇编程序/jasmin 代码以了解到底发生了什么(例如:对于 C++ g++ -S test.cpp 创建 test.s 文件,其中包含汇编代码)

关于c# - 双重和舍入很难,但这太疯狂了,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19833420/

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