Click here to Skip to main content
15,885,546 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
C
#include<stdio.h>
#include<math.h>
#include<stdlib.h>
void bisect(float *p,int n,int a);
float value(float *p,int n,int a);
int main()
{
    int a,i;
    float *p;
    printf("enter the degree of the polynomial\n");
    scanf("%d",&a);
    p=(float *) malloc(a*sizeof(float));
    for(i=0;i<=a;i++)
    {
        printf("enter the coefficient of x^%d\n",i);
        scanf("%f",p+i);
    }
    for(i=-100;i<100;i++)
    {


        if(value(p,i,a)*value(p,i+1,a)<0)
        {
            bisect(p,i,a);
        }
    }
    return 0;
}
float value(float *p,int n,int a)
{
    float sum=0;
    int i;
    for(i=0;i<=a;i++)
    {
        sum=sum+*(p+i)*pow(n,i);
    }
    return sum;
}
void bisect(float *p,int n,int a)
{
    float j,k,l;
    int i;
    j=n;k=n+1;l=(j+k)/2;
    for(i=0;i<50;i++)
    {
        if(value(p,j,a)*value(p,l,a)<0)
        {
            j=j;k=l;l=(j+k)/2;
        }
       else if(value(p,l,a)*value(p,k,a)<0)
       {
           l=(l+k)/2;j=l;
       }
    }
    printf("the root of the equation is %f\n",l);
}


This is done by using bisection method, and i know that the code isn't optimized , i am unable to derive any root from my algorithm though, i want to find out any logical errors as i could find none after much investigation. I would like to know if there is any fault with the equating of data types. thanks in advance.
Posted
Updated 11-Jun-15 14:12pm
v2
Comments
Mohibur Rashid 11-Jun-15 20:13pm    
Have you tried to debug it with your debugger?

1 solution

If you want other people to look at your code you must use sensible variable names. Have a look at this: http://www2.lv.psu.edu/ojj/courses/cmpsc-201/numerical/bisection.html[^]

I won't give you code because this is homework but:

1. Fix this:
C#
p=(float *) malloc(a*sizeof(float));
for(i=0;i<=a;i++)


2. Critical - Change declaration to:

C++
double value(float *p, double x, int a);


and fix implementation.

3. Also:
C++
double j,k,l;


4. In main
C#
#include <iostream>
using namespace std;


and

C#
cin.ignore();
cin.get();

return 0;


Use values from link as your test.
 
Share this answer
 
v3

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900