java - Convert for loop into a recursive function -
this homework problem. i'm having trouble converting following recursive function:
public class integrate { public static double integrate(int a, int b, int steps) { double sum=0; double delta = 1.0 * (b - a)/steps; double x = a; double f = 0.5*x*x + 3*x + 5; (int = 0; i< steps; i++) { x = x + delta; double fr = 0.5*x*x + 3*x + 5; double area = f * delta + 0.5*(fr - f)*delta; sum += area; f = fr; } return sum; } public static void main(string [] args) { int a, b, step; = integer.parseint(args[0]); b = integer.parseint(args[1]); step = integer.parseint(args[2]); system.out.format("integral %f\n", integrate(a,b,step)); } }
this have far output not same original code. can't figure out wrong
public class integrate { public static double integrate(int a, int b, int steps) { double sum=0; int i=0; sum = rintegrate(a, b, steps, i, sum); return sum; } public static double rintegrate(int a, int b, int steps, int i, double sum) { double delta = 1.0 * (b - a)/steps; double x = a; double f = 0.5*x*x + 3*x + 5; if (i<steps) { x = x + delta; double fr = 0.5*x*x + 3*x + 5; double area = f * delta + 0.5*(fr - f)*delta; sum += area; f = fr; i++; rintegrate(a, b, steps, i, sum); } return sum; } public static void main(string[] args) { int a, b, step; = integer.parseint(args[0]); b = integer.parseint(args[1]); step = integer.parseint(args[2]); system.out.format("integral %f\n", integrate(a,b,step)); } }
i'm not going analyze problem, here observations have
if (i<steps) { x = x + delta; double fr = 0.5*x*x + 3*x + 5; double area = f * delta + 0.5*(fr - f)*delta; sum += area; f = fr; i++; rintegrate(a, b, steps, i, sum); } return sum;
everything between sum += area;
, return sum;
superfluous.
- you're setting
f
fr
, never usef
after that. if wantf
different next time, maybe can pass parameter recursive function - you're recursively calling
rintegrate(...)
, you're not doing value returns. might want use value.
you should think recursion using smaller version of problem solve itself.
here's code problem assuming have function: segment
calculates size of first segment given a
, , delta
rintegrate(a, b, steps) { if(steps <= 1) { delta = b-a; return segment(a, delta) } else { delta = (b-a)/steps return segment(a, delta) + rintegrate(a+delta, b, steps-1) } }
Comments
Post a Comment