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 であることがわかります。これは、長方形の数に関係があるのではないかと思います。誰でも助けることができますか?

4

1 に答える 1

0

次のような別のループが必要です

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);

アイデアは、幅 = w の sumOfArea が幅 = 2w の sumOfArea とほぼ同じ (つまり、イプシロン内) になるまで、四角形の幅を減らし続けるということです。

Newton-Cotesなど、より高速でより正確な統合アルゴリズムがありますが、この問題について選択の余地はないと思います。

于 2013-04-18T03:01:33.467 に答える