了解蛛网代码
Understanding a Cobweb code
我正在尝试 运行 Mathematica 中的蜘蛛网代码,我需要以下脚本:
ClearAll[CobwebPlot]
Options[CobwebPlot]=Join[{CobStyle->Automatic},Options[Graphics]];
CobwebPlot[f_,start_?NumericQ,n_,xrange:{xmin_,xmax_},opts:OptionsPattern[]]:=Module[{cob,x,g1,coor},
cob=NestList[f,N[start],n];
coor = Partition[Riffle[cob,cob],2,1];
coor[[1,2]]=0;
cobstyle=OptionValue[CobwebPlot,CobStyle];
cobstyle=If[cobstyle===Automatic,Red,cobstyle];
g1=Graphics[{cobstyle,Line[coor]}];
Show[{Plot[{x,f[x]},{x,xmin,xmax},PlotStyle->{{Thick,Black},Black}],g1},FilterRules[{opts},Options[Graphics]]]
]
Manipulate[CobwebPlot[Sqrt[3#-1]&,\[Alpha],40,{0,5},PlotRange->{{0,4.5},{0,3.65}},Frame->True,Axes->False,CobStyle->Directive[Dashed,Red],PlotRangePadding->None],{\[Alpha],0.5,4.375}]
我在网上找到了这个脚本,但我不明白某些功能,例如以下字符的用途是什么,# 和 &,在代码的Manipulate[]段中:
Manipulate[CobwebPlot[Sqrt[3#-1]&,\[Alpha],40,{0,5},PlotRange->{{0,4.5},{0,3.65}},Frame->True,Axes->False,CobStyle->Directive[Dashed,Red],PlotRangePadding->None],{\[Alpha],0.5,4.375}]
你能帮帮我吗?
参见 this Mathematica documentation page on pure functions, or what other languages call anonymous functions 或 lambda 函数。
举个可爱的例子,假设你有函数
doItTwice[x_,f_] := f[f[x]];
现在假设您要使用此函数对数字 7 进行两次平方。一种方法是像这样定义一个平方函数:
square[x_] := x^2;
doItTwice[7, square]
好吧,有一种更简洁的方法可以将平方函数简单地写成纯函数,看起来像 (#^2)&
。 #
是纯函数的参数,&
只是表示它是一个纯函数。实际上括号甚至都不是必需的,所以你可以写 #^2&
。不管怎样,下面的代码现在是二次平方七的更简洁的方法:
doItTwice[7, (#^2)&]
我正在尝试 运行 Mathematica 中的蜘蛛网代码,我需要以下脚本:
ClearAll[CobwebPlot]
Options[CobwebPlot]=Join[{CobStyle->Automatic},Options[Graphics]];
CobwebPlot[f_,start_?NumericQ,n_,xrange:{xmin_,xmax_},opts:OptionsPattern[]]:=Module[{cob,x,g1,coor},
cob=NestList[f,N[start],n];
coor = Partition[Riffle[cob,cob],2,1];
coor[[1,2]]=0;
cobstyle=OptionValue[CobwebPlot,CobStyle];
cobstyle=If[cobstyle===Automatic,Red,cobstyle];
g1=Graphics[{cobstyle,Line[coor]}];
Show[{Plot[{x,f[x]},{x,xmin,xmax},PlotStyle->{{Thick,Black},Black}],g1},FilterRules[{opts},Options[Graphics]]]
]
Manipulate[CobwebPlot[Sqrt[3#-1]&,\[Alpha],40,{0,5},PlotRange->{{0,4.5},{0,3.65}},Frame->True,Axes->False,CobStyle->Directive[Dashed,Red],PlotRangePadding->None],{\[Alpha],0.5,4.375}]
我在网上找到了这个脚本,但我不明白某些功能,例如以下字符的用途是什么,# 和 &,在代码的Manipulate[]段中:
Manipulate[CobwebPlot[Sqrt[3#-1]&,\[Alpha],40,{0,5},PlotRange->{{0,4.5},{0,3.65}},Frame->True,Axes->False,CobStyle->Directive[Dashed,Red],PlotRangePadding->None],{\[Alpha],0.5,4.375}]
你能帮帮我吗?
参见 this Mathematica documentation page on pure functions, or what other languages call anonymous functions 或 lambda 函数。
举个可爱的例子,假设你有函数
doItTwice[x_,f_] := f[f[x]];
现在假设您要使用此函数对数字 7 进行两次平方。一种方法是像这样定义一个平方函数:
square[x_] := x^2;
doItTwice[7, square]
好吧,有一种更简洁的方法可以将平方函数简单地写成纯函数,看起来像 (#^2)&
。 #
是纯函数的参数,&
只是表示它是一个纯函数。实际上括号甚至都不是必需的,所以你可以写 #^2&
。不管怎样,下面的代码现在是二次平方七的更简洁的方法:
doItTwice[7, (#^2)&]