#!/usr/bin/ruby # from Dominik Geisel include Math def f(f,x) eval(f) end print "enter function (example sin(x): " formula = STDIN.gets.chomp print "first border: " a = STDIN.gets.chomp.to_f print "second border: " b = STDIN.gets.chomp.to_f print "number of intervals: " intervals = STDIN.gets.chomp.to_i n = intervals / 2 h = (b - a) / (2 * n) print "\nlength of one interval: ",h,"\n" # fill an array with the function values on (a + step) array = [f(formula,a)] while a <= b a = a + h array = array + [f(formula,a)] end # get even sum i = 2 evensum = 0 while i < intervals evensum = evensum + array[i] i = i+2 end # get odd sum i = 1 oddsum = 0 while i < intervals oddsum = oddsum + array[i] i = i+2 end # calculate the integral integral = h/3 * ( array[0] + array[intervals] + (2*evensum) + (4*oddsum) ) print "Integral: ",integral,"\n"