简体   繁体   English

计算未输出预期答案

[英]Calculation not outputting expected answer

I'm trying to work out the arctan of a number using the formula: 我正在尝试使用公式计算数字的反正切值:

arctan(x) = x - x^3/3 + x^5/5 - x^7/7...

I have to calculate it to 20 decimal places. 我必须将其计算为小数点后20位。 The answer should be 0.78539.... 答案应该是0.78539....

This is the code I have written, including some debugging statements. 这是我编写的代码,包括一些调试语句。 The problem is in the calculation I think but I just can't see it. 我认为问题出在计算上,但是我看不到它。 Could someone point me in the right direction please? 有人可以指出我正确的方向吗?

EDIT : Can't use the atan function, has to be manually calculated using a double variable from user input. 编辑:不能使用atan函数,必须使用来自用户输入的double变量手动计算。

#include <iomanip>
#include <cstdlib>
#include <iostream>
#include <cmath>
using namespace std;

int main(void)
{
 double x;
 int i;
 int j;
 int y=3;

  cout<<"Please enter the number you wish to calculate the arctan of:"<<endl;
  cin>>x;

   //Calculate arctan of this number
   cout<<x;
   cout<<"\n";
   cout<<y;
   cout<<"\n";

   cout<<"Start\n";

   x=x-(pow(x,y)/y);
   y=y+2;
   cout <<  setprecision (20) << x;
   cout<<"=x before loop\n";
   cout<<y;
   cout<<"=y before loop\n";

   for(i=0;i<9;i++)
    {
     x=x+(pow(x,y)/y);
      cout<<x;
      cout<<"=x1 in loop\n";
     y=y+2;
      cout<<y;
      cout<<"=y1 in loop\n";

     x-(pow(x,y)/y);
      cout<<x;
      cout<<"=x2 in loop\n";
     y=y+2; 
      cout<<y;
      cout<<"=y2 in loop\n";
    }
return 0;

}

Well, your x is changing! 好吧,你的x正在改变! You probably want to use a different variable to store the value computed so far and the argument to your function. 您可能想要使用其他变量来存储到目前为止计算出的值和函数的参数。 That said, don't expect to precise outputs because all those computations involve rounding. 就是说,不要指望精确的输出,因为所有这些计算都涉及舍入。

This line: 这行:

 x-(pow(x,y)/y);

might have something to do with your problem. 可能与您的问题有关。

I would strong advise you use the inbuilt atan function, it is more than likely been well optimised for you architecture, as well as being a standard function recognised by most C++ programmers. 我强烈建议您使用内置的atan函数,它很可能已经为您的体系结构进行了优化,并且是大多数C ++程序员认可的标准函数。

#include <cmath>
#include <iostream>    

int main()
{
    double d;
    std::cout << "enter number" << std::endl;
    std::cin  >> d;
    std::cout << "atan of: " << d 
              << " is "      << std::atan(d) 
              << std::endl;
    return 0;
}

I agree with @Mystical. 我同意@Mystical。 I don't think you're going to get 20 digits of precision out of a double. 我认为您不会从双精度中获得20位精度。 I think you need a long double (if that exists on your system) or, perhaps you need to implement your own big-num class... 我认为您需要一个长双精度型(如果系统中存在),或者可能需要实现自己的bignum类。

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

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