资源简介
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
评论
共有 条评论