C++ 计算比 double 或 long double 更精确
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14637621/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
C++ calculating more precise than double or long double
提问by Terence Chow
I'm teaching myself C++ and on this practice questionit asks to write code that can calculate PI to >30 digits. I learned that double / long double are both 16 digits precise on my computer.
我正在自学 C++,在这个练习题上,它要求编写可以将 PI 计算为 >30 位的代码。我了解到 double / long double 在我的计算机上都是 16 位精确的数字。
I think the lesson of this question is to be able to calculate precision beyond what is available. Therefore how do I do this? Is it possible?
我认为这个问题的教训是能够计算超出可用范围的精度。因此,我该怎么做?是否可以?
my code for calculating Pi right now is
我现在计算 Pi 的代码是
#include "stdafx.h"
#include <iostream>
#include <math.h>
#include <iomanip>
using namespace std;
int main(){
double pi;
pi = 4*atan(1.0);
cout<<setprecision(30)<<pi;
return 0;
}
Output is to 16 digits and pi to 30 digits is listed below for comparison.
下面列出了输出为 16 位和 pi 为 30 位的结果以供比较。
3.1415926535897931
3.141592653589793238462643383279
Any suggestions for increasing precision or is this something that won't matter ever? Alternatively if there is another lesson you think I should be learning here feel free to offer it. Thank you!
任何提高精度的建议,或者这永远不会重要?或者,如果您认为我应该在这里学习其他课程,请随时提供。谢谢!
采纳答案by Mats Petersson
You will need to perform the calculation using some other method than floating point. There are libraries for doing "long math" such as GMP.
您将需要使用浮点数以外的其他方法来执行计算。有一些用于进行“长数学”的库,例如GMP。
If that's not what you're looking for, you can also write code to do this yourself. The simplest way is to just use a string, and store a digit per character. Do the math just like you would do if you did it by hand on paper. Adding numbers together is relatively easy, so is subtracting. Doing multiplication and division is a little harder.
如果这不是您想要的,您也可以自己编写代码来执行此操作。最简单的方法是只使用一个字符串,并为每个字符存储一个数字。做数学就像你在纸上手工做的那样。将数字加在一起相对容易,减法也是如此。做乘法和除法有点难。
For non-integer numbers, you'll need to make sure you line up the decimal point for add/subtract...
对于非整数,您需要确保将小数点对齐以进行加/减...
It's a good learning experience to write that, but don't expect it to be something you knock up in half an hour without much thought [add and subtract, perhaps!]
写下它是一个很好的学习体验,但不要指望它是你在半小时内不加思索地敲出来的东西[加减,也许!]
回答by Tomilov Anatoliy
You can use quad math, builtin type __float128
and q
/Q
suffixes in GCC/clang.
您可以在 GCC/clang 中使用quad math、内置类型__float128
和q
/Q
后缀。
#include <stdio.h>
#include <quadmath.h>
int main ()
{
__float128 x = strtoflt128("1234567891234567891234567891234566", nullptr);
auto y = 1.0q;
printf("%.Qf", x + y); // there is quadmath_snprintf, but this also works fine
return 0;
}