資源簡介
1.給定初值x(0)及精度ε,若||▽f(x(0))||2≤ε則x(0)即為近似極小值
2.若||▽f(x(0))||2>ε,用適當步長 按下式計算
3.一般,若||▽f(x(k))||2≤ε,則x(k)為近似極小值,否則用適當步長 確定下一個近似值,直到滿足精度為止。
用爬山法求f(x,y)=1/(x2+y2+2)的最大值
代碼片段和文件信息
import?java.applet.applet;
import?java.awt.BorderLayout;
import?java.util.*;
import?java.awt.*;
import?java.awt.event.*;
import?java.awt.event.WindowAdapter;
import?com.sun.j3d.utils.applet.Mainframe;
import?com.sun.j3d.utils.geometry.*;
import?com.sun.j3d.utils.universe.*;
/*061300607??2008?4?2-2008?4-12?j3d1.4版本
?爬山算法求到山頂*/
import?javax.media.j3d.*;
import?javax.vecmath.*;
import?javax.swing.*;
import?javax.swing.event.*;
import?com.sun.j3d.utils.behaviors.mouse.MouseRotate;
import?com.sun.j3d.utils.behaviors.mouse.MouseZoom;
import?com.sun.j3d.utils.behaviors.mouse.MouseTranslate;
import?javax.swing.Timer;
import?com.sun.j3d.utils.geometry.Sphere;
public?class?hill?extends?applet?implements?ActionListener
{
private?SimpleUniverse?universe;
private?JButton?start;
private?JTextField?tip?=?new?JTextField(“狀態“);
private?JTextField?X?=?new?JTextField(5);
private?JTextField?Y?=?new?JTextField(5);
private?JLabel?lX?=?new?JLabel(“X的值“?SwingConstants.RIGHT);//文字置右
private?JLabel?lY?=?new?JLabel(“Y的值“?SwingConstants.RIGHT);//文字置右
private?Transform3D?transform?=?new?Transform3D();
private?TransformGroup?tg?=?new?TransformGroup();
private?float?e?=?0.0000001f;//最小值
private?float?xinput?yinput;//輸入進去的x的值和y的值
private?float?step;//步長
private?JPanel?jtop;//添加面板
GridLayout?grid;
Sphere?sphere;
public?hill()
{
}
/////////////////////////////////數學公式///////////////////////////////////////
public?float?f(float?x?float?y)
{
return?(float)(1?/?(x?*?x?+?y?*?y?+?2));
}
public?float?fx(float?x?float?y)//關于x的一階導
{
return?(float)(-2?*?x?/?((x?*?x?+?y?*?y?+?2)?*?(x?*?x?+?y?*?y?+?2)));
}
public?float?fy(float?x?float?y)//關于y的一階導
{
return?(float)(-2?*?y?/?((x?*?x?+?y?*?y?+?2)?*?(x?*?x?+?y?*?y?+?2)));
}
public?float?fxy2(float?x?float?y)//二階導
{
return?(float)(4?*?(x?*?x?+?y?*?y)?/?((x?*?x?+?y?*?y?+?2)?*?(x?*?x?+?y?*?y?+?2)?*?(x?*?x?+?y?*?y?+?2)?*?(x?*?x?+?y?*?y?+?2)));
}
public?void?init()//applet初始化
{
start?=?new?JButton(“開始“);
Canvas3D?canvas?=?new?Canvas3D(SimpleUniverse.getPreferredConfiguration());
canvas.setFocusable(true);?//聚焦畫布
canvas.requestFocus();
setLayout(new?BorderLayout());
start.setBackground(Color.white);
tip.setBackground(Color.white);
lX.setBackground(Color.white);
lY.setBackground(Color.white);
X.setBackground(Color.white);
Y.setBackground(Color.white);
start.setForeground(new?Color(211?151?242));
tip.setForeground(new?Color(211?151?242));
lX.setForeground(new?Color(211?151?242));
lY.setForeground(new?Color(211?151?242));
X.setForeground(new?Color(211?151?242));
Y.setForeground(new?Color(211?151?242));
xinput?=?3f;//初始化x
yinput?=?3f;//初始化y,若未有輸入則一切按照初始化設定
step?=?0.5f;
jtop?=?new?JPanel();
grid?=?new?GridLayout(1?5?1?1);
jtop.setLayout(grid);
jtop.setBackground(Color.white);
jtop.add(lX);
jtop.add(X);
jtop.add(lY);
jtop.add(Y);
jtop.add(s
評論
共有 條評論