-3

I have the following code

/*
    KENDALL WEIHE
    CS321 HW2 PROBLEM 3
    PURPOSE: COMPUTE THE 5TH STEP OF NEWTONS METHOD TO ESTIMATE THE ROOT OF A FUNCTION
    INTPUTS: INITIAL X0 = 1.5
    OUTPUTS: ESTIMATED ROOT AFTER 5 ITERATIONS
*/

#include <stdio.h>

int main(int argc, char *argv[]) {
    //f(x) = -x^3 + x^2 + x + 1
    //f'(x) = -3x^2 + 2x + 1
    //l(x) = f'(x)(x - x0) + f(x)
    //l(x) = (-3x0^2 + 2x0 + 1)(x - x0) + (-x0^3 + x0^2 + x0 + 1)
    //where x0 = x sub 0 || x nought 
    //substitute x0, solve for x
    //x becomes new x0, iterate 5 times
    //solving for the root we find
        //0 = l(x) 
        //x = [4x0^3 + x0^2 - 1]/[3x0^2 + 2x0 + 1]
    int i;
    int x0 = 1.5;
    int x;
    for (i=0;i<5;i++){
        x = (4*x0^3 + x0^2 - 1)/(3*x0^2 + 2*x0 + 1);
        x0 = x;
    }
    printf("%d",x);
}

It's a fairly straight forward program as long as you understand newtons method (slide 16) http://www.cs.uky.edu/~jzhang/CS321/lecture2.pdf

I'm getting 0 as the output. Any ideas?

SOLUTION

I made a stupid mistake thinking the ^ operator was for exponents (Homer Simpson dough) => the correct operator is by using the pow() function

Kendall Weihe
  • 163
  • 3
  • 16

3 Answers3

4
 int x0 = 1.5;   // you want double or float I think . prefer double

And in this expression -

 x = (4*x0^3 + x0^2 - 1)/(3*x0^2 + 2*x0 + 1);

This ^ does not mean what you think (or what you expect from it) . It is Binary XOR Operator in C.

Either write it manually like this - x0's cube -> x0*x0*x0 .

Or use function pow from header <math.h> .

1. declare x0 and x as double.

2. calculate x0's cube as

pow(x,3);     
ameyCU
  • 15,956
  • 2
  • 22
  • 40
1
  1. Replace all int with double. An int will truncate to integral values.

  2. Rewrite x0 ^ 3 to x0 * x0 * x0 etc. (I prefer to not use pow for small integral powers, but handcode the multiplication). ^ in c is the XOR operator, not exponentiation.

  3. Rewrite printf("%d",x); to printf("%f",x); once you've changed the type of x. If you don't do this then your program behaviour will be undefined.

Bathsheba
  • 220,365
  • 33
  • 331
  • 451
1

The ^ is binary XOR Operator in C.

For power calculation you can use pow(). But before use include math.h

ashiquzzaman33
  • 5,451
  • 5
  • 29
  • 39