📄 golddiv.java
字号:
import java.awt.*;
import java.awt.event.*;
/**
*
*
* @author bobo
* @version 1.00 06/12/04
*/
public class GoldDiv{
public static double Pi=3.1415926;
public static void main(String args[]){
Frame f=new Frame("黄金分割搜索");
Button b1=new Button(" draw cosX ");
Button b2=new Button("搜索Xmax=cosX");
Panel p=new Panel();
p.setBackground(Color.yellow);
f.add(p,"South");
p.add(b1);
p.add(b2);
f.setBounds(100,100,600,400);
Listener1 bh1=new Listener1(f);
Listener2 bh2=new Listener2(f);
Listener3 bh3=new Listener3(f);
f.addWindowListener(bh1);
b1.addActionListener(bh2);
b2.addActionListener(bh3);
f.setVisible(true);
}
}
class Listener1 extends WindowAdapter{
Listener1(Frame f){
this.f=f;
}
private Frame f;
public void windowClosing(WindowEvent e){
System.exit(0);
}
}
class Listener2 implements ActionListener {
Listener2(Frame f){
this.f=f;
}
private Frame f;
public void actionPerformed(ActionEvent e){
Graphics g=f.getGraphics();
g.drawLine(10,250,490,250);
g.drawLine(250,100,250,340);
g.drawString("0",242,262);
g.drawString("x",490,262);
g.drawString("y",254,105);
g.drawLine(250,100,248,104);
g.drawLine(250,100,252,104);
g.drawLine(490,250,486,248);
g.drawLine(490,250,486,252);
g.drawString("1",242,150);
g.drawString("-π/2",98,262);
g.drawString("π/2",382,262);
for(int x=10;x<=490;x++){
double double_y=250-(Math.cos((x-250)*(GoldDiv.Pi/300)))*(300/GoldDiv.Pi);
f.getGraphics().drawString(".",x,(int)double_y);
for(int i=0;i<100000;i++);
}
g.drawString("y=cos x",395,240);
}
}
class Listener3 implements ActionListener{
Listener3(Frame f){
this.f=f;
}
private Frame f;
private double x1,y1,x2,y2,a,b;
private int count=0;
public void actionPerformed(ActionEvent e){
a=100.00;b=400.00;
x1=a+0.328*(b-a);x2=a+0.618*(b-a);
y1=250-(Math.cos((x1-250)*(GoldDiv.Pi/300)))*(300/GoldDiv.Pi);
y2=250-(Math.cos((x2-250)*(GoldDiv.Pi/300)))*(300/GoldDiv.Pi);
while(count<=15){
if(y1>y2){
Graphics g=f.getGraphics();
g.setColor(Color.blue);
g.drawLine((int)((x1+x2)/2),250, (int)((x1+x2)/2), (int)(250-(Math.cos((((x1+x2)/2)-250)*(GoldDiv.Pi/300)))*(300/GoldDiv.Pi)));
for(int i=0;i<10000000;i++);
a=x1;x1=x2;y1=y2;
x2=a+0.618*(b-a);
y2=250-(Math.cos((x2-250)*(GoldDiv.Pi/300)))*(300/GoldDiv.Pi);
}
else{
Graphics g=f.getGraphics();
g.setColor(Color.blue);
g.drawLine((int)((x1+x2)/2),250, (int)((x1+x2)/2), (int)(250-(Math.cos((((x1+x2)/2)-250)*(GoldDiv.Pi/300)))*(300/GoldDiv.Pi)));
for(int i=0;i<10000000;i++);
b=x2;x2=x1;y2=y1;
x1=a+0.328*(b-a);
y1=250-(Math.cos((x1-250)*(GoldDiv.Pi/300)))*(300/GoldDiv.Pi);
}
count++;
if((int)x1==250||(int)x2==250){
Graphics g=f.getGraphics();
g.setColor(Color.green);
g.drawLine(250,250,260,260);
g.drawString("x=0时y取得最大值1",263,262);
Graphics h=f.getGraphics();
h.setColor(Color.pink);
h.drawLine(250,250, 250, (int)(250-(Math.cos((250-250)*(GoldDiv.Pi/300)))*(300/GoldDiv.Pi)));
break;
}
}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -