Write a program, derivative.c, to approximate the derivatives of ex, cos(x) and
ID: 3922539 • Letter: W
Question
Write a program, derivative.c, to approximate the derivatives of ex, cos(x) and sin(x) at x = 0 using the limits
dex dx
x=0
= lim h0
eh 1 h
dcos(x) dx
x=0
= lim h0
cos(h) 1 h
dsin(x) dx
x=0
= lim h0
sin(h) h
Your program should use values of h = 1/2,1/4,1/8··· ,1/2n, where n is read from the keyboard, as shown here:
Enter n for h = 1/2 down to 1/2^n: 20
Your program output should be written to the le derivativeout.txt and should look like:
h Dexp(x) Dcos(x) Dsin(x) -----------------------------------0.500000 1.297443 -0.244835 0.958851 0.250000 1.136102 -0.124350 0.989616 0.125000 1.065188 -0.062419 0.997398 0.062500 1.031911 -0.031240 0.999349 . . . . . . . . . . . .
For marking purposes run your program with n = 20.
Explanation / Answer
Code:
#include<stdio.h>
#include<conio.h>
#include<math.h>
void Derivative(int n)
{
FILE *fp;
fp = fopen("derivativeout.txt", "w");
double h=0.5;
int k=1;
double der1=0.999;
double der2=0.999;
double der3=0.999;
fprintf(fp,"h Dexp(x) Dcos(x) Dsin(x)");
fprintf(fp," ");
//finding derivatives
while(k!=n)
{
h=pow(0.5,k);
der1=(exp(h)-1)/h;
der2=(cos(h)-1)/h;
der3=(sin(h))/h;
k++;
//writing to file
fprintf(fp,"%lf %lf %lf %lf",h,der1,der2,der3);
fprintf(fp," ");
}
}
int main()
{
int n;
printf("Enter n for h = 1/2 down to 1/2^n: ");
scanf("%d",&n);
Derivative(n);
getch();
return 0;
}
Output:
h Dexp(x) Dcos(x) Dsin(x)
0.500000 1.297443 -0.244835 0.958851
0.250000 1.136102 -0.124350 0.989616
0.125000 1.065188 -0.062419 0.997398
0.062500 1.031911 -0.031240 0.999349
0.031250 1.015789 -0.015624 0.999837
0.015625 1.007853 -0.007812 0.999959
0.007813 1.003916 -0.003906 0.999990
0.003906 1.001956 -0.001953 0.999997
0.001953 1.000977 -0.000977 0.999999
0.000977 1.000488 -0.000488 1.000000
0.000488 1.000244 -0.000244 1.000000
0.000244 1.000122 -0.000122 1.000000
0.000122 1.000061 -0.000061 1.000000
0.000061 1.000031 -0.000031 1.000000
0.000031 1.000015 -0.000015 1.000000
0.000015 1.000008 -0.000008 1.000000
0.000008 1.000004 -0.000004 1.000000
0.000004 1.000002 -0.000002 1.000000
0.000002 1.000001 -0.000001 1.000000
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.