#include<stdio.h>
float r0,r1; /*initial approximations of root */
float r; /*root*/
struct polynomial {
int number_of_terms;
int exponent[10];
float coefficient[10];
} poly;
float power(float x,int n) {
int i;
float pow=1;
for(i=0;i<n;i++)
pow = pow*x;
return pow;
}
void store_poly() {
int counter=0;
printf("\tEnter the number of terms for your polynomial .... ");
scanf("%d",&poly.number_of_terms);
while(counter<poly.number_of_terms) {
printf("\tEnter the value of coefficient for term %d .... ",counter+1);
scanf("%f",&poly.coefficient[counter]);
printf("\tEnter the value of its exponent .... ");
scanf("%d",&poly.exponent[counter]);
counter++ ;
}
printf("\n\n\tEnter initial approximations(two) of the root ......");
scanf("%f %f",&r0,&r1);
}
float value_at(float x) { /* to calculate f(x) */
int counter=0;
float value=0.00;
while(counter<poly.number_of_terms) {
value += poly.coefficient[counter] * power(x,poly.exponent[counter]);
counter++;
}
return value;}
void print_poly() {
int length=0;
printf("\t----------------------------------------------------------------------------------------\n");
printf("\n\tThe Entered polynomial is as follows ..... ");
while(length<poly.number_of_terms) {
if(poly.coefficient[length]!=0.0)
printf("(%f * X^ %d) ",poly.coefficient[length],poly.exponent[length]);
if(length!= poly.number_of_terms-1)
printf("+ ");
length++ ;
}
printf(" = 0 \n");
printf("\t------------------------------------------------------------------------------------------\n");
}
float find_root() {
int i;
for(i=0;i<5;i++) {
r=(r0*value_at(r1)-r1*value_at(r0))/(value_at(r1)-value_at(r0));
r0=r1;
r1=r;
}
return r;}
main() {
printf("\t********************************************************************\n");
printf("\t DEMONSTRATION OF SECANT METHOD\n");
printf("\t********************************************************************\n");
printf("\t ENTER THE POLYNOMIAL ........\n\n");
store_poly();
print_poly();
printf("\n\t===============================================\n");
printf("\t Calculated value of Root (Secant method) = %f\n",find_root());
printf("\t================================================\n");
}
No comments:
Post a Comment
Do you think this information useful or was not up to the mark? Comment if you have any advices or suggestions about the post.