Mathematica を使って関数を作る方法を教えてください.
Mathematica には定義済みの何百もの関数がありますが,Mathematica の最も強力な側面の1つは,定義されていない操作のためのユーザ独自の関数が作れる点です.
基本的な関数
Mathematica で関数を定義する際は,関数に名前を付け,変数を指定し,出力を決定します.次の例ではpolyfunctionという関数を定義します.「: =」の左にあるアンダースコア(_)は関数の定義に値を渡します.
![[Graphics:Images/index2_gr_41.gif]](http://library.wolfram.com/howtos/functions/Images/index2_gr_41.gif)
この関数に任意の入力を与えて評価すると,適切な式が返されます.
![[Graphics:Images/index2_gr_42.gif]](http://library.wolfram.com/howtos/functions/Images/index2_gr_42.gif)
![[Graphics:Images/index2_gr_43.gif]](http://library.wolfram.com/howtos/functions/Images/index2_gr_43.gif)
![[Graphics:Images/index2_gr_44.gif]](http://library.wolfram.com/howtos/functions/Images/index2_gr_44.gif)
![[Graphics:Images/index2_gr_45.gif]](http://library.wolfram.com/howtos/functions/Images/index2_gr_45.gif)
関数のプロット
次の例ではpolyfunctionによって返された出力のプロットの仕方を詳細に見て行きます.この例では,PlotStyleオプションを使って最初のプロットは青く,2番目のプロットは赤くしてあります.
![[Graphics:Images/index2_gr_46.gif]](http://library.wolfram.com/howtos/functions/Images/index2_gr_46.gif)
![[Graphics:Images/index2_gr_47.gif]](http://library.wolfram.com/howtos/functions/Images/index2_gr_47.gif)
関数を多くの点で評価する
ユーザ定義の関数の値の表を作ります.この例では の各値についてpolyfunctionを評価します.
![[Graphics:Images/index2_gr_50.gif]](http://library.wolfram.com/howtos/functions/Images/index2_gr_50.gif)
![[Graphics:Images/index2_gr_51.gif]](http://library.wolfram.com/howtos/functions/Images/index2_gr_51.gif)
任意の値のセットについて関数を評価することもできます.例えば,次の値のリストに従ってpolyfunctionを評価したいとします.
![[Graphics:Images/index2_gr_52.gif]](http://library.wolfram.com/howtos/functions/Images/index2_gr_52.gif)
![[Graphics:Images/index2_gr_53.gif]](http://library.wolfram.com/howtos/functions/Images/index2_gr_53.gif)
Map関数を使うとvaluelistの各値にpolyfunctionを適用することができます.
![[Graphics:Images/index2_gr_54.gif]](http://library.wolfram.com/howtos/functions/Images/index2_gr_54.gif)
![[Graphics:Images/index2_gr_55.gif]](http://library.wolfram.com/howtos/functions/Images/index2_gr_55.gif)
関数の反復
関数を反復する,つまり出力を次の入力に使って関数を繰り返し評価する必要があることが,しばしばあります.例えば,newtonfunctionという,本質的にNewton法を再現した関数を作ったとします.
![[Graphics:Images/index2_gr_56.gif]](http://library.wolfram.com/howtos/functions/Images/index2_gr_56.gif)
![[Graphics:Images/index2_gr_57.gif]](http://library.wolfram.com/howtos/functions/Images/index2_gr_57.gif)
NestやNestListを使うと関数の出力に同じ関数を繰り返し適用することができます.
これでnewtonfunctionを前の回の出力に繰り返し適用することができます.
NestListはこの場合はx = 2
から始め,指定した通りにnewtonfunctionをその出力に適用します.
![[Graphics:Images/index2_gr_59.gif]](http://library.wolfram.com/howtos/functions/Images/index2_gr_59.gif)
![[Graphics:Images/index2_gr_60.gif]](http://library.wolfram.com/howtos/functions/Images/index2_gr_60.gif)
NestはNestListと違って,newtonfunctionに作用するときに初期値や2次的な繰返しは返しません.Nestを使っても結果は同じですが,Nestは最終的な結果だけを返し,中間のステップは返しません.
![[Graphics:Images/index2_gr_61.gif]](http://library.wolfram.com/howtos/functions/Images/index2_gr_61.gif)
![[Graphics:Images/index2_gr_62.gif]](http://library.wolfram.com/howtos/functions/Images/index2_gr_62.gif)
|