当前位置:   article > 正文

pi六轴算法_蒙特卡洛算法求PI

public int getcanvaswidth() { return canvaswidth; }

利用蒙特卡洛法随机生成任意点,求出PI

源码

import java.awt.*;

import java.util.LinkedList;

import javax.swing.*;

public class AlgoFrame extends JFrame{

private int canvasWidth;

private int canvasHeight;

public AlgoFrame(String title, int canvasWidth, int canvasHeight){

super(title);

this.canvasWidth = canvasWidth;

this.canvasHeight = canvasHeight;

AlgoCanvas canvas = new AlgoCanvas();

setContentPane(canvas);

pack();

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

setResizable(false);

setVisible(true);

}

public AlgoFrame(String title){

this(title, 1024, 768);

}

public int getCanvasWidth(){return canvasWidth;}

public int getCanvasHeight(){return canvasHeight;}

// data

private MonteCarloPiData data;

public void render(MonteCarloPiData data){

this.data = data;

repaint();

}

private class AlgoCanvas extends JPanel{

public AlgoCanvas(){

// 双缓存

super(true);

}

@Override

public void paintComponent(Graphics g) {

super.paintComponent(g);

Graphics2D g2d = (Graphics2D)g;

// 抗锯齿

RenderingHints hints = new RenderingHints(

RenderingHints.KEY_ANTIALIASING,

RenderingHints.VALUE_ANTIALIAS_ON);

hints.put(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);

g2d.addRenderingHints(hints);

// 具体绘制

AlgoVisHelper.setStrokeWidth(g2d, 3);

AlgoVisHelper.setColor(g2d, AlgoVisHelper.Blue);

Circle circle = data.getCircle();

AlgoVisHelper.strokeCircle(g2d, circle.getX(), circle.getY(), circle.getR());

for(int i = 0 ; i < data.getPointsNumber() ; i ++){

Point p = data.getPoint(i);

if(circle.contain(p))

AlgoVisHelper.setColor(g2d, AlgoVisHelper.Red);

else

AlgoVisHelper.setColor(g2d, AlgoVisHelper.Green);

AlgoVisHelper.fillCircle(g2d, p.x, p.y, 3);

}

}

@Override

public Dimension getPreferredSize(){

return new Dimension(canvasWidth, canvasHeight);

}

}

}

import javax.swing.*;

import java.awt.*;

import java.awt.geom.Ellipse2D;

import java.awt.geom.GeneralPath;

import java.awt.geom.Line2D;

import java.awt.geom.Rectangle2D;

import java.lang.InterruptedException;

public class AlgoVisHelper {

private AlgoVisHelper(){}

public static final Color Red = new Color(0xF44336);

public static final Color Pink = new Color(0xE91E63);

public static final Color Purple = new Color(0x9C27B0);

public static final Color DeepPurple = new Color(0x673AB7);

public static final Color Indigo = new Color(0x3F51B5);

public static final Color Blue = new Color(0x2196F3);

public static final Color LightBlue = new Color(0x03A9F4);

public static final Color Cyan = new Color(0x00BCD4);

public static final Color Teal = new Color(0x009688);

public static final Color Green = new Color(0x4CAF50);

public static final Color LightGreen = new Color(0x8BC34A);

public static final Color Lime = new Color(0xCDDC39);

public static final Color Yellow = new Color(0xFFEB3B);

public static final Color Amber = new Color(0xFFC107);

public static final Color Orange = new Color(0xFF9800);

public static final Color DeepOrange = new Color(0xFF5722);

public static final Color Brown = new Color(0x795548);

public static final Color Grey = new Color(0x9E9E9E);

public static final Color BlueGrey = new Color(0x607D8B);

public static final Color Black = new Color(0x000000);

public static final Color White = new Color(0xFFFFFF);

public static void strokeCircle(Graphics2D g, int x, int y, int r){

Ellipse2D circle = new Ellipse2D.Double(x-r, y-r, 2*r, 2*r);

g.draw(circle);

}

public static void fillCircle(Graphics2D g, int x, int y, int r){

Ellipse2D circle = new Ellipse2D.Double(x-r, y-r, 2*r, 2*r);

g.fill(circle);

}

public static void strokeRectangle(Graphics2D g, int x, int y, int w, int h){

Rectangle2D rectangle = new Rectangle2D.Double(x, y, w, h);

g.draw(rectangle);

}

public static void fillRectangle(Graphics2D g, int x, int y, int w, int h){

Rectangle2D rectangle = new Rectangle2D.Double(x, y, w, h);

g.fill(rectangle);

}

public static void setColor(Graphics2D g, Color color){

g.setColor(color);

}

public static void setStrokeWidth(Graphics2D g, int w){

int strokeWidth = w;

g.setStroke(new BasicStroke(strokeWidth, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND));

}

public static void pause(int t) {

try {

Thread.sleep(t);

}

catch (InterruptedException e) {

System.out.println("Error sleeping");

}

}

public static void putImage(Graphics2D g, int x, int y, String imageURL){

ImageIcon icon = new ImageIcon(imageURL);

Image image = icon.getImage();

g.drawImage(image, x, y, null);

}

public static void drawText(Graphics2D g, String text, int centerx, int centery){

if(text == null)

throw new IllegalArgumentException("Text is null in drawText function!");

FontMetrics metrics = g.getFontMetrics();

int w = metrics.stringWidth(text);

int h = metrics.getDescent();

g.drawString(text, centerx - w/2, centery + h);

}

}

import java.awt.*;

import java.util.LinkedList;

import javax.swing.*;

public class AlgoVisualizer {

private static int DELAY = 40;

private MonteCarloPiData data;

private AlgoFrame frame;

private int N;

public AlgoVisualizer(int sceneWidth, int sceneHeight, int N){

if(sceneWidth != sceneHeight)

throw new IllegalArgumentException("This demo must be run in a square window!");

this.N = N;

Circle circle = new Circle(sceneWidth/2, sceneHeight/2, sceneWidth/2);

data = new MonteCarloPiData(circle);

// 初始化视图

EventQueue.invokeLater(() -> {

frame = new AlgoFrame("Monte Carlo", sceneWidth, sceneHeight);

new Thread(() -> {

run();

}).start();

});

}

public void run(){

for(int i = 0 ; i < N ; i ++){

if( i % 100 == 0) {

frame.render(data);

AlgoVisHelper.pause(DELAY);

System.out.println(data.estimatePi());

}

int x = (int)(Math.random() * frame.getCanvasWidth());

int y = (int)(Math.random() * frame.getCanvasHeight());

data.addPoint(new Point(x, y));

}

}

public static void main(String[] args) {

int sceneWidth = 800;

int sceneHeight = 800;

int N = 200000;

AlgoVisualizer vis = new AlgoVisualizer(sceneWidth, sceneHeight, N);

}

}

import java.awt.*;

public class Circle {

private int x, y, r;

public Circle(int x, int y, int r){

this.x = x;

this.y = y;

this.r = r;

}

public int getX(){ return x; }

public int getY(){ return y; }

public int getR(){ return r; }

public boolean contain(Point p){

return Math.pow(p.x - x, 2) + Math.pow(p.y - y, 2) <= r*r;

}

}

import java.util.LinkedList;

import java.awt.*;

public class MonteCarloPiData {

private Circle circle;

private LinkedList points;

private int insideCircle = 0;

public MonteCarloPiData(Circle circle){

this.circle = circle;

points = new LinkedList();

}

public Circle getCircle(){

return circle;

}

public int getPointsNumber(){

return points.size();

}

public Point getPoint(int i){

if(i < 0 || i >= points.size())

throw new IllegalArgumentException("out of bound in getPoint!");

return points.get(i);

}

public void addPoint(Point p){

points.add(p);

if(circle.contain(p))

insideCircle ++;

}

public double estimatePi(){

if(points.size() == 0)

return 0.0;

int circleArea = insideCircle;

int squareArea = points.size();

return (double)circleArea * 4 / squareArea;

}

}

首先随机生成20000个点,截图如下:

在再后面添个0,如下:

由于电脑问题,跑了将近1分钟,电量警告了。两次对比,精度提高了。

凌晨1点了,该洗洗睡了。明日再战......

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/从前慢现在也慢/article/detail/118590
推荐阅读
相关标签
  

闽ICP备14008679号