makecode的圆周率计算程序

micro:bit编程、教学、展示
STEM
回复
头像
shaoziyang
帖子: 3917
注册时间: 2019年 10月 21日 13:48

makecode的圆周率计算程序

#1

帖子 shaoziyang »

2018年的3月14日,也是常说的圆周率日,很多公司在这一天会发布和圆周率相关的内容。makecode就增加了一个计算圆周率的小程序,它通过特殊的算法可以快速计算圆周率π,不过有效位数比较低,大概是小数点后2-3位。
 
 
makecode圆周率计算.jpg
makecode圆周率计算.jpg (60.81 KiB) 查看 3261 次
 

如果上面的图看不清也没有关系,可以直接在浏览器中运行:

https://makecode.microbit.org/_YKEHsxY2vJsR

头像
shaoziyang
帖子: 3917
注册时间: 2019年 10月 21日 13:48

Re: makecode的圆周率计算程序

#2

帖子 shaoziyang »

代码: 全选

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
帖子: 3917
注册时间: 2019年 10月 21日 13:48

Re: makecode的圆周率计算程序

#3

帖子 shaoziyang »

程序的原理是产生0-r之间的随机数(x, y),这些数对应的点位于一个边长是r的正方形中。如果点的坐标平方和小于r的平方,说明点位于半径是 r 的四分之一圆弧中。通过计算点的落于圆弧的数量和总数的比,就可以估算圆周率了。

回复

  • 随机主题
    回复总数
    阅读次数
    最新文章