function simpson(f, a, b, eps)
local olds = 0
local n = 8
local i
local slocal start = tonumber(os.time())
local running = true
while running dolocal h = (b - a) / n
local s = f(a) + f(b)
for i = 1, n - 1, 2 do
s = s + 4 * f(a + i * h)
endfor i = 2, n - 2, 2 do
s = s + 2 * f(a + i * h)
ends = s * (h / 3)
print("n = ", n, " I = ", s)
if math.abs(s - olds) > eps then
n = n * 2
olds = s
else
running = false
end
endlocal elapsed = os.difftime(tonumber(os.time()), start)
print("Time elapsed: ", elapsed)return s
endfunction func(x)
return math.sin(x)
endsimpson(func, 0, math.pi / 2, 0.000000001)
- Replaced blogja
- A hozzászóláshoz be kell jelentkezni
- 733 megtekintés
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?
- A hozzászóláshoz be kell jelentkezni
numerikus intergrálás link
--
"my mind had skipped town and left me behind to pay the rent"
- A hozzászóláshoz be kell jelentkezni
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.
- A hozzászóláshoz be kell jelentkezni
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;
}
- A hozzászóláshoz be kell jelentkezni