0

I'm trying to make a calculator that produces the left hand riemann sum for the equation y = x - x^2, from the bounds 0 to 2. The problem is, I keep getting 0.0 for all my solutions. If anyone could tell me what I'm doing wrong, that would much appreciated.

import java.lang.Math;
public class LeftHandSum {


public static void main(String[] args) {

    int [] n = {2,10,100,1000,10000}; //number of steps in each summation
    int a = 0;
    int b = 2;
    int H = 0;
    double x = 0;       

    for (int j = 0; j < 4; j++)
    {
        double dX = (b-a)/n[j];
        for (int i = 1; i < n[j]; i++)
        {
            x = a + (i-1)*dX;
            H += (x - Math.pow(x,2));               
        }
        double solution = H*dX;
        System.out.println(solution);
    }
  }
}
user3512387
  • 69
  • 1
  • 1
  • 6

1 Answers1

0

you are using integer division in

(b-a)/n[j];

as long as n[j] is bigger than (b-a), it will always return zero. you need to cast it to double before division.

ilj
  • 859
  • 8
  • 18