Some math related code for calculatin binomial coef, nth-fibonacci and sin
This commit is contained in:
parent
65d8891c0e
commit
715f6af296
3 changed files with 136 additions and 0 deletions
36
sin.c
Normal file
36
sin.c
Normal file
|
|
@ -0,0 +1,36 @@
|
|||
#include <stdio.h>
|
||||
|
||||
#define HALFPI 1.5707963268
|
||||
|
||||
// Compute factorial iteratively
|
||||
double factorial(int n) {
|
||||
double result = 1.0;
|
||||
for (int i = 2; i <= n; ++i) {
|
||||
result *= i;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
double abs_double(double x) { return x < 0 ? -x : x; }
|
||||
|
||||
// SICP-style iterative approximation for sin(x)
|
||||
double sin_iter(double x) {
|
||||
double term = x; // First term of the series
|
||||
double sum = term; // Initial sum
|
||||
// double prev_sum;
|
||||
int n = 1; // Starting from x^3/3!
|
||||
|
||||
do {
|
||||
// prev_sum = sum;
|
||||
term *= -x * x / ((2 * n) * (2 * n + 1)); // Next term in series
|
||||
sum += term;
|
||||
++n;
|
||||
} while (abs_double(term) > 1e-10); // Stop when term is sufficiently small
|
||||
|
||||
return sum;
|
||||
}
|
||||
|
||||
int main() {
|
||||
printf("Approximated sin(pi/2) = %.10f\n", sin_iter(HALFPI));
|
||||
return 0;
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue