- #1
- 2,076
- 140
Homework Statement
This is not really a homework problem, but something is just so far off about this I had to ask. Note this is written in C.
Homework Equations
The Attempt at a Solution
Here's some simple code that computes values of ##\sin(x)## and ##\cos(x)## using their Taylor expansions. After six terms, the approximation exceeds the computer's ability to represent it:
Code:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
long double sinxSeries(int, double);
long double cosxSeries(int, double);
int factorial(int);
int main(){
printf("sin(pi/2) = %Lf \n",sinxSeries(6, M_PI/2));
printf("cos(pi/2) = %Lf \n",cosxSeries(6, M_PI/2));
return 0;
}
long double sinxSeries(int n, double x) {
long double returnSum = 0;
for(int i=0;i<n;i++)
returnSum += pow(-1,i) * (pow(x, 2*i + 1))/(factorial(2*i + 1));
return returnSum;
}
long double cosxSeries(int n, double x) {
long double returnSum = 0;
for(int i=0;i<n;i++)
returnSum += pow(-1,i) * (pow(x, 2*i))/(factorial(2*i));
return returnSum;
}
int factorial(int n) {
return(n <= 1 ? 1 : n*factorial(n-1));
}
This code produces the following output (note one of the outputs is horrendous):
Code:
sin(pi/2) = 1.000000
cos(pi/2) = -0.000000
Program ended with exit code: 0
Negative zero?
When I change this line:
Code:
printf("cos(pi/2) = %Lf \n",cosxSeries(6, M_PI/2));
To this:
Code:
printf("cos(pi/2) = %Lf \n",cosxSeries(7, M_PI/2));
I get positive zero:
Code:
sin(pi/2) = 1.000000
cos(pi/2) = 0.000000
Program ended with exit code: 0
What happened here exactly?
Last edited: