lua的閉包真的很強大!
function derivative(f,delta)
delta=delta or 1e-5
return function(x)
return (f(x+delta)-f(x))/delta
endendfunction integral (f,delta)
delta=delta or 1e-5
return function(begin,endn)
local sp=0
for i=begin,endn,delta do
sp=sp+f(i)
endreturn sp*delta
endendc=integral(math.cos)
print(math.sin(5.2),c(0,5.2))
積分近似值,將區域面積分成若干矩形後求和。
function f(x)
return
endo1=f(10)
o2=f(20)
print(o1.get(),o2.get())
o1.set(100)
o2.set(300)
print(o1.get(),o2.get())
10 20 100 300
function newpoly(tab)
local tablenth=#tab
return function(x)
local sp,nowx=tab[1],1
for i=2,tablenth,1 do
nowx=nowx*x
sp=sp+nowx*tab[i]
endreturn sp
endendf=newpoly()
print(f(0),f(5),f(10))
function disk(cx,cy,r)
return function(x,y)
return (x-cx)^2+(y-cy)^2<=r^2
endendfunction rect(left,right,bottom,up)
return function(x,y)
return left<=x and x<=right and bottom<=y and y<=up
endendfunction complement(r)
return function(x,y)
return not r(x,y)
endendfunction union(r1,r2)
return function(x,y)
return r1(x,y) or r2(x,y)
endendfunction intersection(r1,r2)
return function(x,y)
return r1(x,y) and r2(x,y)
endendfunction difference(r1,r2)
return function(x,y)
return r1(x,y) and not r2(x,y)
endendfunction translate(r,dx,dy)
return function(x,y)
return r(x+dx,y+dy)
endendfunction plotpbm(outputfile,r,m,n)
local outputf=io.open(outputfile,"w")
outputf:write("p1\n",m," ",n,"\n")
for i=1,n do
local y=(n-i*2)/n
for j=1,m do
local x=(j*2-m)/m
outputf:write(r(x,y) and "1" or "0")
endoutputf:write("\n")
endendcircle=disk(0,0,1)
--rectangle=rect(-0.5,0.5,-0.5,0.5)
plotpbm("moon.pbm",difference(circle,translate(circle,-0.3,0)),500,500)
--plotpbm("moon.pbm",difference(circle,translate(circle,0.3,0)),500,500)
pbm位**件可以用photoshop開啟。
function rect(left,right,bottom,up)
return function(x,y)
return left<=x and x<=right and bottom<=y and y<=up
endendfunction rotate(r,deg)
return function(x,y)
local rad=math.atan(y,x)-math.rad(deg)
local sp=(x^2+y^2)^(1/2)
if x==0 and y==0 then
rad=0
endreturn r(sp*math.cos(rad),sp*math.sin(rad))
endendfunction plotpbm(outputfile,r,m,n)
local outputf=io.open(outputfile,"w")
outputf:write("p1\n",m," ",n,"\n")
for i=1,n do
local y=(n-i*2)/n
for j=1,m do
local x=(j*2-m)/m
outputf:write(r(x,y) and "1" or "0")
endoutputf:write("\n")
endendrectangle=rect(-0.6,0.6,-0.6,0.6)
plotpbm("rotaterect.pbm",rotate(rectangle,60),500,500)
極座標變換後得到旋轉前圖形對應x、y值,注意處理x=0,y=0的點。 《Lua程式設計 第4版 》 第7章練習答案
function exercise7 1and2 filename1,filename2 local inputf,outputf if filename1 and filename2 then inputf io.open filename1,r local filetest io.open fi...
《Lua程式設計 第4版 》 第5章練習答案
monday sunday sunday 一樣,都指向該錶。a.a.a.a 3,執行的是該錶的索引 a 賦值為3,之後的a.a.a.a將會引發異常,因現a.a 3,而非表。在方括號裡寫索引值 tab for i,j in pairs tab do io.write i,j,n endfunction...
Lua程式設計第4版第6章課後練習答案
6.1 略 6.2 用lselect 2,函式 6.3function f63 local t table.pack t t.n nil t.n t.n 1return table.unpack t end print f63 2 3,4 5 6.4 說下思路 pair每乙個元素,把每個元素都隨機從...