2018年的3月14日,也是常说的圆周率日,很多公司在这一天会发布和圆周率相关的内容。makecode就增加了一个计算圆周率的小程序,它通过特殊的算法可以快速计算圆周率π,不过有效位数比较低,大概是小数点后2-3位。
如果上面的图看不清也没有关系,可以直接在浏览器中运行:
https://makecode.microbit.org/_YKEHsxY2vJsR
makecode的圆周率计算程序
- shaoziyang
- 帖子: 3919
- 注册时间: 2019年 10月 21日 13:48
Re: makecode的圆周率计算程序
代码: 全选
let pir = 0
let pid = 0
let pin = 0
let y = 0
let x = 0
let inside = 0
// A simple Monte-Carlo simulation to approximate Pi.
//
// number of points
//
let n = 1000000
// radius of the circle
let r = 4000
// radius square
let r2 = r * r
basic.forever(function () {
inside = 0
for (let index = 0; index < n; index++) {
// generate a point within the square
x = Math.randomRange(0, r)
y = Math.randomRange(0, r)
// test if the point is within the circle sqrt(x**2 +
// y**2) < r ==> x**2 + y**2 < r**2
if (x * x + y * y < r2) {
inside += 1
}
}
// surface of a square: 4 * r * r surface of a circle:
// r * r * pi => inside / n ~= (r*r*pi) / (4*r*r) ~=
// pi / 4 pi = inside / n * 4
pin = inside * 4
// only integer arithmetic here...
pid = Math.idiv(pin, n)
pir = pin % n
// show results
basic.showLeds(`
# # # # #
. # . # .
. # . # .
. # . # .
. # . . #
`)
basic.showString(" " + pid + "." + pir)
})
- shaoziyang
- 帖子: 3919
- 注册时间: 2019年 10月 21日 13:48
Re: makecode的圆周率计算程序
程序的原理是产生0-r之间的随机数(x, y),这些数对应的点位于一个边长是r的正方形中。如果点的坐标平方和小于r的平方,说明点位于半径是 r 的四分之一圆弧中。通过计算点的落于圆弧的数量和总数的比,就可以估算圆周率了。
-
- 随机主题
- 回复总数
- 阅读次数
- 最新文章
-
- 1回复总数
- 687 阅读次数
- 最新文章 由 shaoziyang
2021年 10月 3日 20:43
-
- 7回复总数
- 1117 阅读次数
- 最新文章 由 zwjiang
2021年 10月 4日 09:10
-
- 3回复总数
- 1393 阅读次数
- 最新文章 由 shaoziyang
2021年 10月 4日 20:37