0

I'm trying to write an algorithm to find the roots of f(x) = x^4 -4x +1 I'm supposed to get the 4 roots of this function 2 reals and imaginary. I write this algorithm in c. But do not if it's well written and what kind of initial guess I should input for a and b, because everytime I run the program it gives me different numbers Here is my code and thanks for your help:

#include<stdio.h>
#include<math.h>
int computeroots(double, double, double, double);
int main()
{
    double a ,b, soln;
    double  epsilon = pow(10, -8);
    int MaxIter;
    printf("please enter an initial guess for a: \n");
    scanf("%ld",&a);
    printf("please enter a second guess for b: \n");
    scanf("%ld", &b);
    printf("please enter the maximum number of iteration: \n");
    scanf("%d", &MaxIter);
    soln = computeroots(a, b, epsilon, MaxIter);
    printf("Here is the solution: %d \n", soln);
    return 0;
}

int computeroots(double a, double b, double epsilon, double MaxIter)
{
    float FA = pow(a,4) - 4*a + 1;
    float FB = pow(b,4) - 4*b +1;
    float FP;
    int i =1;
    float p;
    if(FA * FB < 0)
    {
            while(i<MaxIter)
            {
                    p = a + (b-a)/2;
                    FP = pow(p,4) - 4*p +1;
                    if(FP == 0 || (b-a)/2 < epsilon)
                    {
                            return p;
                            break;
                    }
                    i++;
                    if(FA*FP > 0)
                    {
                            a = p;
                            FA = FP;
                    }
                    else
                    {
                            b = p;
                    }


            }
    }
}
user2059456
  • 19
  • 1
  • 2
  • 8
  • 2
    Why does your function only have one return? Why does it return a `float` value as an `int`? What happens when `FA * FB == 0.0` or `FA * FB > 0.0`? Why are you using `float` values instead of `double`? The expression `(b-a)/2 < epsilon` isn't a relative difference; if `a` is bigger than `b`, the condition will be satisfied. – Jonathan Leffler Feb 14 '13 at 07:44
  • you're perfectly right.. I changed the loop to the FOR loop since I know it better and have control over it.. Thanks though – user2059456 Feb 14 '13 at 14:22

1 Answers1

0

I think you have to find the two guesses such that one guess yields you a negative result and the other one gives positive. Wikipedia has an example. The number of iterations can greatly vary depending on the precision and the initial guess. Also don't step down the variable from double to float you will lose precision.

Puck
  • 2,080
  • 4
  • 19
  • 30
Koushik Shetty
  • 2,146
  • 4
  • 20
  • 31