PI is calculated mainly by Monte Carlo method. The code is as follows:
1) pi.pl:
$time 1 = Time (), foreach (1..20000000) { my ($x, $y) = (rand (), Rand ()); if (sqrt ($x * * 2 + $y * * 2) < 1) { $total + = 1; }} $PI = 4.0 * $total/20000000; $time 2 = time ();p rint "PI =", $pi, "time =", $time 2-$time 1;
The Perl script runs as follows, and the average execution time for 20 million times is about 27 seconds:
2) pi.py
Import randomimport Datetimeimport mathstarttime = Datetime.datetime.now () total = 0for I in Xrange (20000000): x, y = r Andom.random (), Random.random () if MATH.SQRT (x * * 2 + y * 2) < 1: total + = 1PI = 4.0 * Total/20000000endtime = Datetime.datetime.now () print "PI =", pi, "time =", (endtime-starttime). seconds
the Python results are as follows, and the average execution time of 20 million is about 30 seconds:
3) Pi.erl
-module (PI)-export ([PI/1]). Pi (n), Pi (n, N, 0) . Pi (n, 0, total)-4.0 * TOTAL/N;PI (n, I, total) , X = Random:uniform (), Y = Random:uniform (), R = ma TH:SQRT (x * x + y * y), if R < 1, pi (N, I-1, total + 1); True--- Pi (N, I-1, total) end.
Erlang runs as follows, and theaverage execution time for 20 million times is about 30 seconds:
4) Pi.c
#include <stdio.h> #include <stdlib.h> #include <time.h> #include <math.h>int main () {Time _t start_time, End_time; Double elapsed_time; Double x, y, pi; Long I, total; Total = 0; Srand ((unsigned) time (0)); Time (&start_time); for (i = 0; i < 20000000; i + +) { x = rand ()/(double) (Rand_max); y = rand ()/(double) (Rand_max); if (sqrt (x * x + y * y) < 1) {Total + = 1; } } PI = 4.0 * total/20000000; Time (&end_time); Elapsed_time = Difftime (End_time, start_time); printf ("total =%d, pi =%f, time =%f", Total, pi, elapsed_time); }
C Run as follows, 20 million times the average execution time is about 3 seconds:
Python, Erlang is quite fast, Perl is a little bit faster, and C is 10 times times the size of their language.
Perl, Python, Erlang, C language running speed comparison