如何求无穷级数的和?
系列
我行为不端的例子:

seq 0 inf | awk '{sum+=(1/$1)} END {print sum}'

是否可以进行这种方法的正确计算或如何用其他方法解决这个问题?

最佳答案

这个级数不收敛。它被称为调和级数,已知它不收敛。
此外,正如一条评论所说,您需要从1开始,而不是从0开始,否则就没有定义:
试试这个:

seq 1 inf | awk '{sum+=(1/$1)} {print sum}'

但是,对于更高的迭代次数,这并不好用,因为数字格式表示不兼容,并且内部使用的数字表示的精度不够。
为了更精确地估计收敛级数的值,你应该使用一个更适合的编程语言,如Java、Python或C++的科学计算软件包。
下面是一个完整的Java工作示例:
import java.math.BigDecimal;
import java.math.MathContext;
import java.math.RoundingMode;

public class SeriesCalculator {

    public static void main(String[] args) {
        MathContext mathContext = new MathContext(100, RoundingMode.HALF_EVEN);

        BigDecimal i = BigDecimal.ONE;
        BigDecimal sum = BigDecimal.ZERO;
        while (true) {
            // calculation for every iteration
            BigDecimal element = BigDecimal.ONE.divide(i, mathContext);
            sum = sum.add(element);

            // show output once for every magnitude
            String iStr = i.toString();
            if (iStr.matches("10*")) {
                int logI10 = iStr.length() - 1;
                System.out.println("i=10^" + logI10 + "; sum = " + sum);
            }

            // preparation of next iteration step
            i = i.add(BigDecimal.ONE);
        }
    }
}

输出:
i=10^0; sum = 1
i=10^1; sum = 2.9289682539682539682539682539682539682539682539682539682539682539682539682539682539682539682539682540
i=10^2; sum = 5.18737751763962026080511767565825315790897212670845165317653395658721955753255049660568776892312041358
i=10^3; sum = 7.485470860550344912656518204333900176521679169708803665773626749957699349165202440959934437411845081421
i=10^4; sum = 9.7876060360443822641784779048516053348592629455776917183894609566816020249431595068001251272900808826142
i=10^5; sum = 12.09014612986342794736321936350421950079369894178220110162752941593818198228230919443164900701935230601448
i=10^6; sum = 14.392726722865723631381127493188587676644800013744311653418433045812958507517995003568298175947219100731214
i=10^7; sum = 16.6953113658598518153991189395404518842498697523730804627851359543562886921742546877116037143701502883133367
i=10^8; sum = 18.99789641385389832441711039422398284185097124497010343881842218865761130260918292544757982666365581248865345
...

10-07 18:40