定积分(黎曼和)的编程实现(java和python实现)

Talk is cheap. Show me the code.

a是积分下限,b是积分上限

f是被积函数

代码如下(Java版本):

public class RiemannSum {
	public static void main(String[] args) {
		final int times = 100000000;
		double a, b;
		double sum = 0;

		a = 1;
		b = 3;
		double delta = (b - a) / times;
		
		for (int i = 1; i <= times; i++) {
			sum += delta * fSin(a + i * delta);
		}
		System.out.println(sum);
	}

	public static double f(double a) {
		return Math.pow(a, 4);
	}
	
	public static double fSin(double a) {
		return Math.sin(a);
	}
}

Python版本:

import math

def f(a):
    return math.pow(a,2)


times = 10000000

riemannSum = 0;

a = 1;
b = 3;
delta = (b - a) / times

for i in range(1,times+1):
    riemannSum += delta * math.sin(a + i * delta)

print(riemannSum)