欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

《Lua程序设计(第4版)》:第9章练习答案

程序员文章站 2022-03-14 12:14:01
...

Lua的闭包真的很强大!

练习9.1

function derivative(f,delta)
  delta=delta or 1e-5
  return function(x)
    return (f(x+delta)-f(x))/delta
  end
end

function 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)
    end
    return sp*delta
  end
end

c=integral(math.cos)
print(math.sin(5.2),c(0,5.2))

积分近似值,将区域面积分成若干矩形后求和。

练习9.2

function F(x)
  return {
    set=function(y)
      x=y
    end,
    get=function()
      return x
    end
  }
end
o1=F(10)
o2=F(20)
print(o1.get(),o2.get())

o1.set(100)
o2.set(300)
print(o1.get(),o2.get())

10 10 100 300

练习9.3

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]
    end
    return sp
  end
end

f=newpoly({3,0,1})
print(f(0),f(5),f(10))

练习9.4

function disk(cx,cy,r)
  return function(x,y)
    return (x-cx)^2+(y-cy)^2<=r^2
  end
end

function rect(left,right,bottom,up)
  return function(x,y)
    return left<=x and x<=right and bottom<=y and y<=up
  end
end

function complement(r)
  return function(x,y)
    return not r(x,y)
  end
end

function union(r1,r2)
  return function(x,y)
    return r1(x,y) or r2(x,y)
  end
end

function intersection(r1,r2)
  return function(x,y)
    return r1(x,y) and r2(x,y)
  end
end

function difference(r1,r2)
  return function(x,y)
    return r1(x,y) and not r2(x,y)
  end
end

function translate(r,dx,dy)
  return function(x,y)
    return r(x+dx,y+dy)
  end
end

function 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")
    end
    outputF:write("\n")
  end
end
circle=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打开。

练习9.5

function rect(left,right,bottom,up)
  return function(x,y)
    return left<=x and x<=right and bottom<=y and y<=up
  end
end

function 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
    end
    return r(sp*math.cos(rad),sp*math.sin(rad))
  end
end

function 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")
    end
    outputF:write("\n")
  end
end

rectangle=rect(-0.6,0.6,-0.6,0.6)
plotPBM("rotaterect.pbm",rotate(rectangle,60),500,500)

极坐标变换后得到旋转前图形对应x、y值,注意处理x=0,y=0的点。

END

相关标签: Lua