C ++中的双精度数字在Windows和Linux中不同。为什么? Linux显示超过20个非零精度数字 [英] Number of precision digits for double in C++ different in windows and Linux. Why? Linux shows more than 20 non-zero precision digits

查看:764
本文介绍了C ++中的双精度数字在Windows和Linux中不同。为什么? Linux显示超过20个非零精度数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

刚刚这样:

double val1=numeric_limits<double>::max();
cout.precision(70);
cout<<"\nVal1: "<<val1;

在Windows中,我开始在17位数字(小数点后16位数字)处获取0。然而,在Linux中,随着我不断增加cout.precision(NUMBER),越来越多的数字保持显示,它们不是零。

In Windows I start getting 0s after 17 digits(16 digits after decimal point). However in Linux, as I keep increasing the cout.precision(NUMBER), more and more digits keep showing and they are not zeros.

此外,运行以下代码在Windows和Linux上都显示15。 Windows系统是32位,Linux一个是64位,如果这有什么区别。

Also, running the following code shows '15' on both Windows and Linux. Windows system is 32 bits and Linux one is 64 bit if that makes any difference.

typedef std::numeric_limits< double > dl;
cout << "\tdigits (decimal):\t" << dl::digits10 << endl;

任何人都可以帮助解释这里发生了什么?
我认为精度数字的数量将在Windows& Linux,因为sizeof(double)是8。

Can any one help with an explanation as to what is going on here? I thought number of precision digits will be same in Windows & Linux since sizeof(double) is 8 on both of them.

推荐答案

打印出 double 在打印出 double 的确切值之前,输出许多位数。可以打印出一个 double 。例如,最接近1/3的 double 具有值:

When you print out a double, you often have to print out many, many digits before you print out the exact value of the double. It is possible to print out a double exactly. For example, the double closest to 1/3 has the value:

0.333333333333333314829616256247390992939472198486328125

打印出这个值需要54位小数点。但是人们说 double 只有 16位精度。什么给了?

Printing out this value exactly requires 54 digits past the decimal point. But people say a double only has about 16 digits of precision. What gives?

当你说一个双精度有16位数字,这意味着你需要至少16位数字,使双生存的往返。也就是说,以下过程保留输入数据:

When you say that a double has 16 digits of precision, that means that you need at least 16 digits to make the double survive a round trip. That is, the following process preserves the input data:

double -> 16 digit decimal -> double

因此,超过16的额外数字不一定是垃圾 只是不必要。根据标准,他们几乎可以是任何东西 - 只要读取结果会给你相同的 double

So the extra digits past 16 aren't necessarily garbage, they're just unnecessary. And according to the standard, they can be almost anything -- as long as reading the result will give you the same double back.

摘要:我的猜测是,Linux上的标准库会打印出double的确切值,而Windows库会截断结果。

The Summary: My guess is that your standard library on Linux is printing out the exact value of the double, and the Windows library is truncating the result. Both actions are permitted by the standard.

你几乎肯定不需要double的确切值,因为浮点数的算术通常是不精确的。

You almost certainly don't need the exact value of a double anyway, since arithmetic on floating point numbers is usually inexact.

这篇关于C ++中的双精度数字在Windows和Linux中不同。为什么? Linux显示超过20个非零精度数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆