【发布时间】:2018-07-23 08:21:09
【问题描述】:
我尝试使用 c 和 Taylor Series 创建自定义 sine 函数,以计算系列中的 10 个术语的 sin,但是当我尝试查找 @987654327 时得到错误的结果@其中x > 6。
它适用于 -5 < x < 5,但超出该范围的任何内容都不会产生正确的结果。
我希望sin(10) 返回接近-0.5440 的值,但得到1418.0269775391
我已将所有内容放在一个文件中,这样更容易。
#include <stdio.h>
#include <stdlib.h>
double factorial(double n);
double power(double n, double pow);
double sine(double n);
// This is supposed to all go in a .c file and reference the .h stuff above
// This is the actual implementation of the functions declared above
double factorial(double n) {
// 0! = 1 so just return it
if(n == 0) {
return 1;
}
// Recursively call factorial with n-1 until n == 0
return n * (factorial(n - 1));
}
double power(double n, double power) {
double result = n;
// Loop as many times as the power and just multiply itself power amount of times
for(int i = 1; i < power; i++) {
result = n * result;
}
return result;
}
double sine(double n) {
double result = n;
double coefficent = 3; // Increment this by 2 each loop
for(int i = 0; i < 10; i++) { // Change 10 to go out to more/less terms
double pow = power(n, coefficent);
double frac = factorial(coefficent);
printf("Loop %d:\n%2.3f ^ %2.3f = %2.3f\n", i, n, coefficent, pow);
printf("%2.3f! = %2.3f\n", coefficent, frac);
// Switch between adding/subtracting
if(i % 2 == 0) { // If the index of the loop is divided by 2, the index is even, so subtract
result = result - (pow/frac); // x - ((x^3)/(3!)) - ((x^5)/(5!))...
} else {
result = result + (pow/frac); // x - ((x^3)/(3!)) + ((x^5)/(5!))...
}
coefficent = coefficent + 2;
printf("Result = %2.3f\n\n", result);
}
return result;
}
// main starting point. This is suppossed to #include "functions.c" which contain the above functions in it
int main(int argc, char** argv) {
double number = atof(argv[1]); // argv[1] = "6"
double sineResult = sine(number);
printf("%1.10f", sineResult);
return (0);
}
【问题讨论】:
-
如果你之前没有尝试过,现在是learn how to debug our programs的好时机。
-
而为什么你要
double number = atof("5")?为什么不简单地double number = 5.0?还是直接拨打sine(5.0)?或者由于该函数采用int参数,int number = 5;或sine(5)? -
您在很多地方都在使用
int。最终其中一个会溢出。例如power(10, 10)不会返回正确答案(因为正确答案是 100 亿,不适合 32 位int)。 -
在
sine(n)中,首先使用n = fmod(n, 2*pi);或等效项.. -
弧度的质量范围缩小是一个比计算
sine()更困难的问题。见https://www.csee.umbc.edu/~phatak/645/supl/Ng-ArgReduction.pdf
标签: c factorial trigonometry taylor-series