Java 写一个无限和的公式,为什么';这不是写好的吗?

Java 写一个无限和的公式,为什么';这不是写好的吗?,java,sum,infinite,Java,Sum,Infinite,我需要在Java中编写一个无穷和来匹配- sqrt(t)*sech(t)^2 dt从t=0到t=无穷(一个从t=0开始,然后在t=无穷结束的无限和。我引用Wolfram Alpha(Mathematica)来比较我的结果) 用更多的数学术语来说,这(本质上)就是程序正在做的事情。我注意到这是平方(双曲)正割。虽然,最大值实际上是无限的- integrate sqrt(t)*sech(t)^2 dt from t=0 to t=1000 为了匹配这个无穷和,我在下面写了一个简短的程序 publi

我需要在Java中编写一个无穷和来匹配-

sqrt(t)*sech(t)^2 dt
t=0
t=无穷
(一个从
t=0
开始,然后在
t=无穷
结束的无限和。我引用Wolfram Alpha(Mathematica)来比较我的结果)

用更多的数学术语来说,这(本质上)就是程序正在做的事情。我注意到这是平方(双曲)正割。虽然,最大值实际上是无限的-

integrate sqrt(t)*sech(t)^2 dt from t=0 to t=1000
为了匹配这个无穷和,我在下面写了一个简短的程序

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;
   }
}
运行该程序的结果是-

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

我很肯定Mathematica没有错。我的程序出了什么问题?

您的解决方案根本不够准确

积分可以用黎曼和来近似

见维基百科

delta x(或者在您的例子中,delta t)越小,结果越好

在您的解决方案中,
delta t=1
,因此近似值不是很好

更好地近似结果的可能解决方案是使用:

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

结果=0.7581278135568323

你不应该在某处进行sqrt吗?这是如何递归的?我没有看到Math.pow(n,s)引用s=0.5的递归。我不确定我是否应该从技术上将其归类为递归(它看起来与我相似,但我在数学方面比Java好得多)。为什么不在循环后打印结果?您使用了哪种数值积分算法?还有,这里没有sqrt(t)谢谢,我明白我的错误了。我有点尴尬,将继续我的程序。
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); 
   }
}
dt=0.00001d