用户工具

站点工具


microbit:趣味程序:makecode:用makecode计算圆周率

2018年的3月14日,也是每年的圆周率日,makecode发布了一个计算圆周率的小程序,它通过特殊的算法可以快速计算圆周率π,不过有效位数比较低,大概是小数点后2-3位。

在线演示

代码:

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 = randint(0, r)
        y = randint(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)
})


purge    随机主题   
microbit/趣味程序/makecode/用makecode计算圆周率.txt · 最后更改: 2021/03/29 21:58 由 shaoziyang · 查看次数: 7245