java - Riemann Integrator Sum Issue -
here code riemann integrator:
public class riemannintegrator { public static void main (string [] args) { double lower = double.parsedouble(args[args.length -2]); double higher = double.parsedouble(args[args.length -1]); double[] coefficients = new double[args.length - 3]; if (args[0].equals("poly")) { (int = 1; < args.length - 2; i++) { coefficients[i-1] = double.parsedouble(args[i]); } system.out.println(integral("poly", coefficients, lower, higher)); } } private static double integral(string s, double[] function, double lowbound, double highbound) { double area = 0; // area of rectangle double sumofarea = 0; // sum of area of rectangles double width = highbound - lowbound; if (s.equals("poly")) { (int = 1; <= ((highbound - lowbound) / width); i++) // represents # of rectangles { system.out.println("rectangles:" + i); (int j = 0; j < function.length; j++) // goes through coefficients { area = width * function[j] * math.pow ( (double)( (i * width + lowbound + (i -1.0) * width + highbound) / 2.0 ),function.length- 1- j); /*above code computes area of each rectangle */ sumofarea += area; } } } width = width / 2.0; system.out.println("polynomial, function (of length), lower boundary, higher boundary."); function.tostring(); system.out.println("lower bound:" + lowbound + ", higher bound: " + highbound + "."); system.out.println("the integral is:"); return sumofarea; } }
it works part, however, math wrong more not, , don't know went wrong. example, if want find sum of function of x^3+2x^2+3x, 2.416667 on calculator, , on wolfram alpha. but, in program, tells me 6. think may have number of rectangles, because tells me 1 rectangle. can help?
you need loop, along lines of
double width = highbound - lowbound; double epsilon = .001; // determines how accurate want solution be, closer 0 = more accurate double prevvalue = -1.0; double curvalue = -1.0; // initialize curvalue negative value greater magnitude epsilon - ensures while loop evaluates true on first pass { ... // loop goes prevvalue = curvalue; curvalue = sumofarea; width /= 2.0; } while(math.abs(prevvalue - curvalue) > epsilon);
the idea keep decreasing rectancles' width until sumofarea width = w more-or-less same (i.e. within epsilon) sumofarea width = 2w.
there faster + more accurate integration algorithms out there e.g. newton-cotes, i'm assuming don't have choice in matter.
Comments
Post a Comment