简体   繁体   English

C ++计算比double或long double更精确

[英]C++ calculating more precise than double or long double

I'm teaching myself C++ and on this practice question it asks to write code that can calculate PI to >30 digits. 我正在自学C ++,在这个实践问题上,它要求编写能够将PI计算到> 30位的代码。 I learned that double / long double are both 16 digits precise on my computer. 我了解到双/长双精度在我的计算机上都是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! 谢谢!

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!] 写这个是一个很好的学习经历,但是不要指望它是半小时内没有多想的东西[加减法,也许!]!

You can use quad math , builtin type __float128 and q / Q suffixes in GCC/clang. 您可以在GCC / clang中使用四元数学 ,内置类型__float128q / 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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM