C ++计算比双精度或更长的双精度 [英] C++ calculating more precise than double or long double

查看:196
本文介绍了C ++计算比双精度或更长的双精度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在教自己的C ++,并在这个练习问题上要求编写代码可以计算PI到> 30位数。我学会了双/长双是在我的电脑上的16位数字精确。

I'm teaching myself C++ and on this practice question it 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.

我认为这个问题的教训是能够计算超过可用的精度。那么我该怎么做呢?可能吗?

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?

现在我计算Pi的代码是

my code for calculating Pi right now is

#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;
}

输出为16位数字,pi至30位数字

Output is to 16 digits and pi to 30 digits is listed below for comparison.

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!

推荐答案

您需要使用除浮点之外的其他方法来执行计算。有一些图书馆可以做长数学,例如 GMP

You will need to perform the calculation using some other method than floating point. There are libraries for doing "long math" such as 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!]

这篇关于C ++计算比双精度或更长的双精度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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