Search code examples
javanewtons-method

Programming Beginner - Java program adapted from C


I'm brand new at writing programs in any language and I'm trying to write a simple Newton-Raphson method which I think works in C (haven't compiled but going from a previous example that did work so I'm making this assumption) but realised that I don't know exactly how to call a method from Java... I'm getting these errors:

NewtRaphEx.java:5: class, interface, or enum expected
double f = (double); 
^
NewtRaphEx.java:6: class, interface, or enum expected
double df = (double); 
^
NewtRaphEx.java:39: class, interface, or enum expected
double f(double x) {
^

I assume I'm calling the f and df methods incorrectly? This is not for a homework question, simply my own practice!

My program so far is:

/* Newton Raphson Method*/

import Scanner.java.util; 

double f = (double); 
double df = (double); 

public class NewtRaphEx {

    public static void main (String[] args) {

        double xn, e_allow, fn, fnew, eps, dfn, dfnew; 
        int n;
        int nMax = 10000;

        e_allow = 0.001;
        xn = 0.6;

        while (eps <= e_allow || n < nMax) {
            for (n = 0; n <= nMax; n++) {
                fn = f(xn); 
                dfn = df(xn);
                dx = -(fn / dfn); 
                xnew = xn + dx; 
                eps = Math.abs(dx / xn);
                n = n + 1; 
                System.out.println("N" + "\t" + "X" + "\t" + "F(x)" + "\t" + "dF(x)" + "\t" + "delX" + "\t" + "X_new" + "\t" + "Epsilon");
                System.out.println(n + "\t" + xn + "\t" + fn + "\t" + dfn + "\t" + dx + "\t" + xnew + "\t" + eps);
            }
        }
    }
}



// Creating Function f = x - cos(3.5x)

double f(double x) {
    return (x - cos(3.5 * x)) 
}

double df (double x) {
    return (1 + sin(3.5 * x))
}

Solution

  • Methods f and df are outside the class. They must be declared inside it. They should be static since they are not bound to an instance and you will call them from a static method.

    This double f = (double); is illegal. You must provide a value or nothing double f;

    sin and cos should be java.lang.Math.sin and java.lang.Math.cos unless you use static import.