[英]Wrong results with cosx (custom function) with functions(noobie)
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define PI 3.14159265
double sin1x(double converted,int i);
double cos1x(double converted,int i);
int main(){
int r,i = 1;
double converted,p,results,results1;
printf("Insert degrees from 0..2π: ");
scanf("%d", &r);
if(r < 0 || r > 360)
{
printf("NOT ACCEPTABLE DEGREES\n");
exit(0);
}
converted = r * PI / 180;
printf("Conversion from degrees to rad = %.3f", converted);
results = sin1x(converted,i);
results1 = cos1x(converted,i);
printf("\nsin(%d) = %.3f\n", r, results);
printf("\nsin(%d) of c = %.3f\n", r,sin(converted));
printf("\ncos(%d) = %.3f\n", r, results1);
printf("\ncos(%d) of c = %.3f\n", r,cos(converted));
return 0;
}
double sin1x(double x, int i)
{
int j = 3;
double sinx,numerator = x,pr;
sinx = numerator;
do
{
pr = numerator;
numerator = pr * x * x / (j * (j - 1));
if(i % 2 == 0)
sinx = sinx + numerator;
else
{
if(i % 2 == 1)
sinx = sinx - numerator;
}
i++;
j+=2;
}
while(fabs(pr - numerator) > 0.000001);
return sinx;
}
double cos1x(double x, int i)
{
int j = 2;
double cosx,numerator = x,pr;
cosx = numerator;
do
{
pr = numerator;
numerator = pr * x * x / (j * (j - 1));
if(i % 2 == 0)
cosx = cosx + numerator;
else
{
if(i % 2 == 1)
cosx = cosx - numerator;
}
i++;
}
while(fabs(pr - numerator) > 0.000001);
return cosx;
}
Hello I try to make a program with cosx and sinx and for some reason I have a problem with cosx.你好,我尝试用 cosx 和 sinx 制作一个程序,但出于某种原因,我对 cosx 有疑问。 I cannot find any issues with my program but the cos results are wrong.Also I have the sin() and cos() functions to compare the results.
我找不到我的程序有任何问题,但 cos 结果是错误的。我还有 sin() 和 cos() 函数来比较结果。 I tried changing j or making another variable to factorial but it didn't change anything.
我尝试更改 j 或将另一个变量设为阶乘,但没有任何改变。
At least these problems:至少这些问题:
Wrong initialization初始化错误
// double cosx,numerator = x,pr;
double cosx,numerator = 1.0,pr;
Missing change to j
缺少对
j
的更改
// Add to `cos1x()` do loop
j += 2;
Coarse PI粗PI
No reason to not use a more precise value.没有理由不使用更精确的值。
// #define PI 3.14159265
#define PI 3.1415926535897932384626433832795
Spelling拼写
Convertion --> Conversion转换--> 转换
Candidate simplification候选简化
double cos1x_alt(double x) {
double xx = x * x;
double term = 1.0;
double sum = term;
for (int i = 1; 1.0 + term != 1.0; i += 2) {
term *= -xx / (i * (i + 1));
sum += term;
}
return sum;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.