Writing a formula for an infinite sum, why doesn't this work as written?

1.8k views Asked by At

I an writing an infinite sum inside Java to match -

sqrt(t)*sech(t)^2 dt from t=0 to t=infinity (An infinite sum starting from t = 0 and then ending at t = infinity. I am referencing Wolfram Alpha (Mathematica) to compare my results).

In more mathematical terms, this is (essentially) what the program is doing. I note that this is squaring (hyperbolic) secant. Although, the maximum is really infinity-

integrate sqrt(t)*sech(t)^2 dt from t=0 to t=1000

To match this infinite sum, I wrote a short program below.

public class TestSum {
   public static void main(String[] args) {
           newForm(0.5);
   }

   public static double newForm(double s) {
    int n = 0;
    double currentSum = 0;

    while (n < 1000) {
        double sech = 1 / Math.cosh(n);
        double squared = Math.pow(sech, 2);
        currentSum = ((Math.pow(n, s))*squared) + currentSum;
        if(n == 999)
            System.out.println("The current sum is " + currentSum);
        n++;
    }
    return currentSum;
   }
}

When I plug this into Mathematica/Wolfram I get -

integrate sqrt(t)*sech(t)^2 dt from t=0 to t=1000
integral_0^1000 sqrt(t) sech^2(t) dt = 0.758128

The result from running the program is -

run:
The current sum is 0.5401365941579325
BUILD SUCCESSFUL (total time: 0 seconds)

I am pretty sure Mathematica isn't wrong. What is wrong with my program?

1

There are 1 answers

1
andih On BEST ANSWER

Your solution simply is not accurate enough.

An integral can be approximated by a Riemann Sum

Riemann Summ

see Riemann Sum on wikipedia.

The result gets better the smaller the delta x (or in your case delta t) becomes.

In your solution delta t = 1, so the approximation is not really good.

The a possible solution to approximate the result better is to use:

public class TestSum {
   public static void main(String[] args) {
          double result= integrate(0, 1000);
          System.out.print("result = " + result );
   }

   public static double integrate(double start, double end) {
    double currentIntegralValue = 0;
    double dt=0.01d;
    double t = start;

    while (Math.abs(end - t) >= dt && t-end < 0) {
        currentIntegralValue += fn(t)*dt;
        t += dt;
    }
    return currentIntegralValue;
   }

   private static double fn(double t) {
        double sech = 1 / Math.cosh(t);
        double squared = Math.pow(sech, 2);
        return  ((Math.pow(t, 0.5))*squared); 
   }
}

result = 0.7579201343666041

You can further improve the result by using a smaller dt.

dt=0.00001d

result = 0.7581278135568323