Legyen tolem is egy csepp Lua

Kis szamolyolas Lua-ban, csak a hecc kedveert. :-)


function simpson(f, a, b, eps)

local olds = 0
local n = 8
local i
local s

local start = tonumber(os.time())

local running = true
while running do

local h = (b - a) / n

local s = f(a) + f(b)

for i = 1, n - 1, 2 do
s = s + 4 * f(a + i * h)
end

for i = 2, n - 2, 2 do
s = s + 2 * f(a + i * h)
end

s = s * (h / 3)

print("n = ", n, " I = ", s)
if math.abs(s - olds) > eps then
n = n * 2
olds = s
else
running = false
end
end

local elapsed = os.difftime(tonumber(os.time()), start)
print("Time elapsed: ", elapsed)

return s
end

function func(x)
return math.sin(x)
end

simpson(func, 0, math.pi / 2, 0.000000001)

Hozzászólások


n = 	8	 I = 	1.000008295524
n = 	16	 I = 	1.0000005166847
n = 	32	 I = 	1.000000032265
n = 	64	 I = 	1.0000000020161
n = 	128	 I = 	1.000000000126
n = 	256	 I = 	1.0000000000079
Time elapsed: 	0

Ez vmi pi közelítő függvény?

Nem, a pi-t a math.pi-ből veszi. De ha jól megnézed, a "simpson" egy integrálóprogram, a főprogram meg kiirogatja, hogy az intervallum "n" részintervallumra osztása esetén mit ad a Simpson formula a sin(x) 0-tól pi/2-ig való integráljára, ami ugye elvileg -cos(pi/2)+cos(0)=0+1.
256 részintervallummal már egész elfogadható eredményt kap.

microtime-mal jobban látszik a futásidő:

Fordítás:


cc -o mtime.so -shared -Wall mtime.c

Használat:


require "mtime"
print(os.microtime())

Kód:


#include "lua.h"
#include "lauxlib.h"
#include "lualib.h"
#include <sys/time.h>
#include <time.h>

int l_mtime(lua_State *L){

	struct timeval tv;
	
	gettimeofday(&tv, NULL);
	lua_pushnumber(L, tv.tv_usec);
	return 1;
}

static const luaL_reg reg_mtime[] = {
	{"microtime", l_mtime},
	{NULL, NULL}
	}; 
int luaopen_mtime(lua_State *L){
	luaL_register(L, "os", reg_mtime);
	return 1;
}