概率算法求解圆周率π

package com.colin;

/**
 * 
 * @author Colin Yan
 * 
 */
public class CalcPI {

	private static boolean isHit(double x, double y) {
		x %= 1.0;
		y %= 1.0;
		return x * x + y * y <= 1.0;
	}

	public static void main(String[] args) {
		int hitTimes = 0;
		int trialTimes = 10000000;

		for (int i = 0; i < trialTimes; i++) {
			double x = Math.random();
			double y = Math.random();
			hitTimes += isHit(x, y) ? 1 : 0;
		}
		System.out.println("PI=" + hitTimes * 4.0D / trialTimes);
	}

}

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,我可以为您提供Python实现蒙特卡洛方法求解圆周率π的代码,并绘制结果图形。 蒙特卡洛方法是一种基于随机数的数值计算方法,用于解决某些数学问题,其中包括计算π的值。通过在一个正方形内随机地生成点,并计算落在正方形内且在圆内的点的数量,可以估算出圆的面积与正方形面积的比值,从而计算出π的值。 以下是Python实现蒙特卡洛方法求解π的代码: ```python import random import math import matplotlib.pyplot as plt # 定义正方形边长和圆的半径 square_length = 2 radius = 1 # 定义生成点的数量 num_points = 10000 # 初始化计数器 num_points_circle = 0 # 初始化存储生成点的列表 x_inside_circle = [] y_inside_circle = [] x_outside_circle = [] y_outside_circle = [] # 生成点并计数 for i in range(num_points): x = random.uniform(-1, 1) y = random.uniform(-1, 1) if math.sqrt(x**2 + y**2) <= radius: num_points_circle += 1 x_inside_circle.append(x) y_inside_circle.append(y) else: x_outside_circle.append(x) y_outside_circle.append(y) # 计算π的值 pi_estimate = 4 * num_points_circle / num_points print("π的估计值为:", pi_estimate) # 绘制图形 fig, ax = plt.subplots() circle = plt.Circle((0, 0), radius, fill=False) ax.add_artist(circle) ax.set_xlim((-1, 1)) ax.set_ylim((-1, 1)) ax.scatter(x_inside_circle, y_inside_circle, color='r', marker='.') ax.scatter(x_outside_circle, y_outside_circle, color='b', marker='.') plt.show() ``` 运行上述代码后,程序将随机生成指定数量的点,并计算出圆内点的数量,从而估算出π的值。最后,程序将绘制一个图形,其中红色的点表示落在圆内的点,蓝色的点表示落在圆外的点,圆的轮廓表示圆的边界。 希望这个代码能够帮助您。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值