Calculating Pi

Материал из Поле цифровой дидактики

There are many ways to calculate pi (π) which is defined by Wikipedia below: Шаблон:Quote

Here are just of few of the methods that have been proposed to calculate this value.

Method One

The script below is one method to calculate pi:

when green flag clicked
set [pi v] to (4)
set [Refreshes v] to (1)
forever
    change [Refreshes v] by (2)
    set [pi v] to ((pi) - ((4)/(Refreshes)))
    change [Refreshes v] by (2)
    set [pi v] to ((pi) + ((4)/(Refreshes)))
end

This script will constantly make the variable π closer and closer to the actual number π.
This is called the Gregory-Leibniz series.

Method Two

Шаблон:Note Below is another method for calculating pi:

when gf clicked
set [pi v] to (3)
set [Refreshes v] to (2)
forever
    set [pi v] to ((pi) + ((4)/((Refreshes) * (((Refreshes) + (1)) * ((Refreshes) + (2))))))
    change [Refreshes v] by (2)
    set [pi v] to ((pi) - ((4)/((Refreshes) * (((Refreshes) + (1)) * ((Refreshes) + (2))))))
    change [Refreshes v] by (2)
end

This is referred to as the Nilakantha series.

Method Three

Шаблон:Note The higher that the variable "n" is, the closer to pi the output will be.

ask [Please enter n:] and wait
set [n v] to (answer)
set [pi v] to ((n) * ([sin v] of ((180) / (n)):: operators ))

This method was used by Archimedes to calculate the original pi. This method can never actually get the exact value of pi using this method, but like all the other methods it can give enough exactness to be used in a project.

Speeding up the Program

One way to make the program much faster is to use a run without screen refresh custom block, however this may cause issues on some mobile devices. To do this, see below:

For Method One

when green flag clicked
set [pi v] to (4)
set [Refreshes v] to (1)
forever
    Update::custom
end

define Update // Run without screen refresh
repeat (100)
    change [Refreshes v] by (2)
    set [pi v] to ((pi) - ((4)/(Refreshes)))
    change [Refreshes v] by (2)
    set [pi v] to ((pi) + ((4)/(Refreshes)))
end

For Method Two

when gf clicked
set [pi v] to (3)
set [Refreshes v] to (2)
forever
    Update method 2 :: custom
end

define Update method 2 //Run without screen refresh
repeat (100)
    set [pi v] to ((pi) + ((4)/((Refreshes) * (((Refreshes) + (1)) * ((Refreshes) + (2))))))
    change [Refreshes v] by (2)
    set [pi v] to ((pi) - ((4)/((Refreshes) * (((Refreshes) + (1)) * ((Refreshes) + (2))))))
    change [Refreshes v] by (2)
end