2013-04-18 1 views
0

다음은 리만 통합에 대한 내 코드입니다 :리만 통합 합계는 문제

그것은 대부분 작동
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")) 
     { 
      for (int i = 1; i < 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 the rectangle 
     double sumOfArea = 0; // Sum of the area of the rectangles 
     double width = highBound - lowBound; 

      if (s.equals("poly")) 
      { 
       for (int i = 1; i <= ((highBound - lowBound)/width); i++) // Represents # of rectangles 
       { 
        System.out.println("Rectangles:" + i); 
        for (int j = 0; j < function.length; j++) // Goes through all the 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 any length), lower boundary, higher boundary."); 
      function.toString(); 
      System.out.println("Lower Bound:" + lowBound + ", Higher Bound: " + highBound + "."); 
      System.out.println("The integral is:"); 
      return sumOfArea; 
    } 



} 

은, 그러나, 수학이 더 자주 못하는 것보다 잘못, 내가 어디로 갔는지 모르겠어요 잘못된. 예를 들어, x^3 + 2x^2 + 3x 함수의 합계를 찾고 싶으면 계산기와 Wolfram Alpha에서 2.416667을 얻습니다. 그러나, 내 프로그램에서, 그것은 내가 6을 얻는다 고 말한다. 나는 그것이 내가 항상 하나의 직사각형을 얻는다는 것을 알려주기 때문에 그것이 직사각형의 수와 관련이있을 것이라고 생각한다. 누구든지 도와 줄 수 있습니까?

답변

0

당신은 아이디어가 다소간 동일 승 당신은 즉 내 (= 폭과 sumOfArea까지 rectancles '폭을 감소 유지하는 것입니다,

double width = highBound - lowBound; 
double epsilon = .001; // This determines how accurate you want the solution to be, closer to zero = more accurate 
double prevValue = -1.0; 
double curValue = -1.0; // initialize curValue to a negative value with greater magnitude than epsilon - this ensures that the while loop evaluates to true on the first pass 
do { 
    ... // this is where your for loop goes 
    prevValue = curValue; 
    curValue = sumOfArea; 
    width /= 2.0; 
} while(Math.abs(prevValue - curValue) > epsilon); 

의 라인을 따라 뭔가를 또 다른 루프를 필요 ε)를 width = 2w 인 sumOfArea로 설정합니다.

더 빠르고 더 정확한 통합 알고리즘이 있습니다. Newton-Cotes,하지만 당신이 그 문제에 대해 선택권이 없다고 가정하고 있습니다.

+0

맞습니다. 나는 그 문제에 대해 선택의 여지가 없다. –