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


i writing infinite sum inside java match -

sqrt(t)*sech(t)^2 dt t=0 t=infinity (an infinite sum starting t = 0 , ending @ t = infinity. referencing wolfram alpha (mathematica) compare results).

in more mathematical terms, (essentially) program doing. note squaring (hyperbolic) secant. although, maximum infinity-

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

to match infinite sum, wrote 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 " + currentsum);         n++;     }     return currentsum;    } } 

when plug mathematica/wolfram -

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

the result running program -

run: current sum 0.5401365941579325 build successful (total time: 0 seconds) 

i pretty sure mathematica isn't wrong. wrong program?

your solution not accurate enough.

an integral can approximated riemann sum

riemann summ

see riemann sum on wikipedia.

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

in solution delta t = 1, approximation not good.

the possible solution approximate result better 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 result using smaller dt.

dt=0.00001d 

result = 0.7581278135568323


Comments

Popular posts from this blog

c# - Validate object ID from GET to POST -

node.js - Custom Model Validator SailsJS -

php - Find a regex to take part of Email -