我正在研究這個程序,它近似於泰勒級數函數。我必須對它進行近似,以使泰勒級數函數停止以0.00001的精度逼近sin函數。換句話說,最後一個近似值減去當前近似值的絕對值小於或等於0.00001。它也以15度爲增量近似從0到360度的每個角度。我的邏輯似乎是正確的,但我不明白爲什麼我得到垃圾值。任何幫助表示讚賞!如何以0.00001([C++],[Taylor Series])的精度結束while循環?
#include <math.h>
#include <iomanip>
#include <iostream>
#include <string>
#include <stdlib.h>
#include <cmath>
double fact(int x){
int F = 1;
for(int i = 1; i <= x; i++){
F*=i;
}
return F;
}
double degreesToRadians(double angle_in_degrees){
double rad = (angle_in_degrees*M_PI)/180;
return rad;
}
using namespace std;
double mySine(double x){
int current =99999;
double comSin=x;
double prev=0;
int counter1 = 3;
int counter2 = 1;
while(current>0.00001){
prev = comSin;
if((counter2 % 2) == 0){
comSin += (pow(x,(counter1))/(fact(counter1)));
}else{
comSin -= (pow(x,(counter1))/(fact(counter1)));
}
current=abs(prev-comSin);
cout<<current<<endl;
counter1+=2;
counter2+=1;
}
return comSin;
}
using namespace std;
int main(){
cout<<"Angle\tSine"<<endl;
for (int i = 0; i<=360; i+=15){
cout<<i<<"\t"<<mySine(degreesToRadians(i));
}
}
將int電流更改爲浮動電流或雙倍電流.. – Phoenix
也在'fact()'中將int F更改爲雙F. – Eugene