WeixiangYan/CodeTransOcean huggingface dataset:
Task: Averages_Mode






PHP: <?php
function mode($arr) {
    $count = array_count_values($arr);
    $best = max($count);
    return array_keys($count, $best);
}

print_r(mode(array(1, 3, 6, 6, 6, 6, 7, 7, 12, 12, 17)));
print_r(mode(array(1, 1, 2, 4, 4)));
?>





Fortran: program mode_test
  use Qsort_Module only Qsort => sort
  implicit none

  integer, parameter    :: S = 10
  integer, dimension(S) :: a1 = (/ -1, 7, 7, 2, 2, 2, -1, 7, -3, -3 /)
  integer, dimension(S) :: a2 = (/  1, 1, 1, 1, 1, 0, 2, 2, 2, 2 /)
  integer, dimension(S) :: a3 = (/  0, 0, -1, -1, 9, 9, 3, 3, 7, 7 /)

  integer, dimension(S) :: o
  integer               :: l, trash

  print *, stat_mode(a1)

  trash = stat_mode(a1, o, l)
  print *, o(1:l)
  trash = stat_mode(a2, o, l)
  print *, o(1:l)
  trash = stat_mode(a3, o, l)
  print *, o(1:l)

contains

  
  
  
  
  
  
  integer function stat_mode(a, others, otherslen, ok)
    integer, dimension(:), intent(in) :: a
    logical, optional, intent(out)    :: ok
    integer, dimension(size(a,1)), optional, intent(out) :: others
    integer, optional, intent(out)    :: otherslen

    
    
    
    integer, dimension(size(a, 1)) :: ta, freq, idx
    integer                        :: rs, i, tm, ml, tf

    if ( present(ok) ) ok = .false.

    select case ( size(a, 1) )
    case (0)  
       return
    case (1)
       if ( present(ok) ) ok = .true.
       stat_mode = a(1)
       return
    case default
       if ( present(ok) ) ok = .true.
       ta = a         
       call sort(ta)  
       freq = 1
       idx = 0
       rs = 1         
       
       do i = 2, size(ta, 1)
          if ( ta(i-1) == ta(i) ) then
             freq(rs) = freq(rs) + 1
          else
             idx(rs) = i-1
             rs = rs + 1
          end if
       end do
       idx(rs) = i-1
         
       ml = maxloc(freq(1:rs), 1)  
       tf = freq(ml)               
       tm = ta(idx(ml))            

       
       if ( present(others) ) then
          i = 1
          others(1) = tm
          do
             freq(ml) = 0
             ml = maxloc(freq(1:rs), 1)
             if ( tf == freq(ml) ) then 
                i = i + 1               
                others(i) = ta(idx(ml))
             else
                exit
             end if
          end do
                
          if ( present(otherslen) ) then
             otherslen = i
          end if

       end if
       stat_mode = tm
    end select

  end function stat_mode

end program mode_test
Task: Averages_Mode






PHP: <?php
function mode($arr) {
    $count = array_count_values($arr);
    $best = max($count);
    return array_keys($count, $best);
}

print_r(mode(array(1, 3, 6, 6, 6, 6, 7, 7, 12, 12, 17)));
print_r(mode(array(1, 1, 2, 4, 4)));
?>
Task: Averages_Mode






PHP: <?php
function mode($arr) {
    $count = array_count_values($arr);
    $best = max($count);
    return array_keys($count, $best);
}

print_r(mode(array(1, 3, 6, 6, 6, 6, 7, 7, 12, 12, 17)));
print_r(mode(array(1, 1, 2, 4, 4)));
?>






Ada: generic
   type Element_Type is private;
   type Element_Array is array (Positive range <>) of Element_Type;
package Mode is

   function Get_Mode (Set : Element_Array) return Element_Array;

end Mode;
Task: Monte Carlo methods



C#: using System;

class Program {
    static double MonteCarloPi(int n) {
        int inside = 0;
        Random r = new Random();

        for (int i = 0; i < n; i++) {
            if (Math.Pow(r.NextDouble(), 2)+ Math.Pow(r.NextDouble(), 2) <= 1) {
                inside++;
            }
        }

        return 4.0 * inside / n;
    }

    static void Main(string[] args) {
        int value = 1000;
        for (int n = 0; n < 5; n++) {
            value *= 10;
            Console.WriteLine("{0}:{1}", value.ToString("#,###").PadLeft(11, ' '), MonteCarloPi(value));
        }
    }
}









Ada: with Ada.Text_IO;                use Ada.Text_IO;
with Ada.Numerics.Float_Random;  use Ada.Numerics.Float_Random;

procedure Test_Monte_Carlo is
   Dice : Generator;
   
   function Pi (Throws : Positive) return Float is
      Inside : Natural := 0;
   begin
      for Throw in 1..Throws loop
         if Random (Dice) ** 2 + Random (Dice) ** 2 <= 1.0 then
            Inside := Inside + 1;
         end if;
      end loop;
      return 4.0 * Float (Inside) / Float (Throws);
   end Pi;
begin
   Put_Line ("     10_000:" & Float'Image (Pi (     10_000)));
   Put_Line ("    100_000:" & Float'Image (Pi (    100_000)));
   Put_Line ("  1_000_000:" & Float'Image (Pi (  1_000_000)));
   Put_Line (" 10_000_000:" & Float'Image (Pi ( 10_000_000)));
   Put_Line ("100_000_000:" & Float'Image (Pi (100_000_000)));
end Test_Monte_Carlo;
Task: Monte Carlo methods

C: #include <stdio.h>
#include <stdlib.h>
#include <math.h>
 
double pi(double tolerance)
{
	double x, y, val, error;
	unsigned long sampled = 0, hit = 0, i;

	do {
		
		for (i = 1000000; i; i--, sampled++) {
			x = rand() / (RAND_MAX + 1.0);
			y = rand() / (RAND_MAX + 1.0);
			if (x * x + y * y < 1) hit ++;
		}

		val = (double) hit / sampled;
		error = sqrt(val * (1 - val) / sampled) * 4;
		val *= 4;

		
		fprintf(stderr, "Pi = %f +/- %5.3e at %ldM samples.\r",
			val, error, sampled/1000000);
	} while (!hit || error > tolerance);
              

	return val;
}

int main()
{
	printf("Pi is %f\n", pi(3e-4)); 
	return 0;
}











Ada: with Ada.Text_IO;                use Ada.Text_IO;
with Ada.Numerics.Float_Random;  use Ada.Numerics.Float_Random;

procedure Test_Monte_Carlo is
   Dice : Generator;
   
   function Pi (Throws : Positive) return Float is
      Inside : Natural := 0;
   begin
      for Throw in 1..Throws loop
         if Random (Dice) ** 2 + Random (Dice) ** 2 <= 1.0 then
            Inside := Inside + 1;
         end if;
      end loop;
      return 4.0 * Float (Inside) / Float (Throws);
   end Pi;
begin
   Put_Line ("     10_000:" & Float'Image (Pi (     10_000)));
   Put_Line ("    100_000:" & Float'Image (Pi (    100_000)));
   Put_Line ("  1_000_000:" & Float'Image (Pi (  1_000_000)));
   Put_Line (" 10_000_000:" & Float'Image (Pi ( 10_000_000)));
   Put_Line ("100_000_000:" & Float'Image (Pi (100_000_000)));
end Test_Monte_Carlo;
Task: Monte Carlo methods


C++: #include<iostream>
#include<math.h>
#include<stdlib.h>
#include<time.h>
 
using namespace std;
int main(){
    int jmax=1000; 
    int imax=1000; 
    double x,y;    
    int hit;       
    srand(time(0));
    for (int j=0;j<jmax;j++){
        hit=0;
        x=0; y=0;
        for(int i=0;i<imax;i++){
            x=double(rand())/double(RAND_MAX);
            y=double(rand())/double(RAND_MAX);
        if(y<=sqrt(1-pow(x,2))) hit+=1; }          
    cout<<""<<4*double(hit)/double(imax)<<endl; }  
}










Ada: with Ada.Text_IO;                use Ada.Text_IO;
with Ada.Numerics.Float_Random;  use Ada.Numerics.Float_Random;

procedure Test_Monte_Carlo is
   Dice : Generator;
   
   function Pi (Throws : Positive) return Float is
      Inside : Natural := 0;
   begin
      for Throw in 1..Throws loop
         if Random (Dice) ** 2 + Random (Dice) ** 2 <= 1.0 then
            Inside := Inside + 1;
         end if;
      end loop;
      return 4.0 * Float (Inside) / Float (Throws);
   end Pi;
begin
   Put_Line ("     10_000:" & Float'Image (Pi (     10_000)));
   Put_Line ("    100_000:" & Float'Image (Pi (    100_000)));
   Put_Line ("  1_000_000:" & Float'Image (Pi (  1_000_000)));
   Put_Line (" 10_000_000:" & Float'Image (Pi ( 10_000_000)));
   Put_Line ("100_000_000:" & Float'Image (Pi (100_000_000)));
end Test_Monte_Carlo;
Task: Monte Carlo methods




Go: package main

import (
    "fmt"
    "math"
    "math/rand"
    "time"
)

func getPi(numThrows int) float64 {
    inCircle := 0
    for i := 0; i < numThrows; i++ {
        
        
        randX := rand.Float64()*2 - 1 
        randY := rand.Float64()*2 - 1 
        
        dist := math.Hypot(randX, randY)
        if dist < 1 { 
            inCircle++
        }
    }
    return 4 * float64(inCircle) / float64(numThrows)
}

func main() {
    rand.Seed(time.Now().UnixNano())
    fmt.Println(getPi(10000))
    fmt.Println(getPi(100000))
    fmt.Println(getPi(1000000))
    fmt.Println(getPi(10000000))
    fmt.Println(getPi(100000000))
}








Ada: with Ada.Text_IO;                use Ada.Text_IO;
with Ada.Numerics.Float_Random;  use Ada.Numerics.Float_Random;

procedure Test_Monte_Carlo is
   Dice : Generator;
   
   function Pi (Throws : Positive) return Float is
      Inside : Natural := 0;
   begin
      for Throw in 1..Throws loop
         if Random (Dice) ** 2 + Random (Dice) ** 2 <= 1.0 then
            Inside := Inside + 1;
         end if;
      end loop;
      return 4.0 * Float (Inside) / Float (Throws);
   end Pi;
begin
   Put_Line ("     10_000:" & Float'Image (Pi (     10_000)));
   Put_Line ("    100_000:" & Float'Image (Pi (    100_000)));
   Put_Line ("  1_000_000:" & Float'Image (Pi (  1_000_000)));
   Put_Line (" 10_000_000:" & Float'Image (Pi ( 10_000_000)));
   Put_Line ("100_000_000:" & Float'Image (Pi (100_000_000)));
end Test_Monte_Carlo;
Task: Monte Carlo methods





Java: public class MC {
	public static void main(String[] args) {
		System.out.println(getPi(10000));
		System.out.println(getPi(100000));
		System.out.println(getPi(1000000));
		System.out.println(getPi(10000000));
		System.out.println(getPi(100000000));
		
	}
	public static double getPi(int numThrows){
		int inCircle= 0;
		for(int i= 0;i < numThrows;i++){
			
			
			double randX= (Math.random() * 2) - 1;
			double randY= (Math.random() * 2) - 1;
			
			double dist= Math.sqrt(randX * randX + randY * randY);
			
			if(dist < 1){
				inCircle++;
			}
		}
		return 4.0 * inCircle / numThrows;
	}
}







Ada: with Ada.Text_IO;                use Ada.Text_IO;
with Ada.Numerics.Float_Random;  use Ada.Numerics.Float_Random;

procedure Test_Monte_Carlo is
   Dice : Generator;
   
   function Pi (Throws : Positive) return Float is
      Inside : Natural := 0;
   begin
      for Throw in 1..Throws loop
         if Random (Dice) ** 2 + Random (Dice) ** 2 <= 1.0 then
            Inside := Inside + 1;
         end if;
      end loop;
      return 4.0 * Float (Inside) / Float (Throws);
   end Pi;
begin
   Put_Line ("     10_000:" & Float'Image (Pi (     10_000)));
   Put_Line ("    100_000:" & Float'Image (Pi (    100_000)));
   Put_Line ("  1_000_000:" & Float'Image (Pi (  1_000_000)));
   Put_Line (" 10_000_000:" & Float'Image (Pi ( 10_000_000)));
   Put_Line ("100_000_000:" & Float'Image (Pi (100_000_000)));
end Test_Monte_Carlo;
Task: Monte Carlo methods







Python: >>> import random, math
>>> throws = 1000
>>> 4.0 * sum(math.hypot(*[random.random()*2-1
	                 for q in [0,1]]) < 1
              for p in xrange(throws)) / float(throws)
3.1520000000000001
>>> throws = 1000000
>>> 4.0 * sum(math.hypot(*[random.random()*2-1
	                 for q in [0,1]]) < 1
              for p in xrange(throws)) / float(throws)
3.1396359999999999
>>> throws = 100000000
>>> 4.0 * sum(math.hypot(*[random.random()*2-1
	                 for q in [0,1]]) < 1
              for p in xrange(throws)) / float(throws)
3.1415666400000002





Ada: with Ada.Text_IO;                use Ada.Text_IO;
with Ada.Numerics.Float_Random;  use Ada.Numerics.Float_Random;

procedure Test_Monte_Carlo is
   Dice : Generator;
   
   function Pi (Throws : Positive) return Float is
      Inside : Natural := 0;
   begin
      for Throw in 1..Throws loop
         if Random (Dice) ** 2 + Random (Dice) ** 2 <= 1.0 then
            Inside := Inside + 1;
         end if;
      end loop;
      return 4.0 * Float (Inside) / Float (Throws);
   end Pi;
begin
   Put_Line ("     10_000:" & Float'Image (Pi (     10_000)));
   Put_Line ("    100_000:" & Float'Image (Pi (    100_000)));
   Put_Line ("  1_000_000:" & Float'Image (Pi (  1_000_000)));
   Put_Line (" 10_000_000:" & Float'Image (Pi ( 10_000_000)));
   Put_Line ("100_000_000:" & Float'Image (Pi (100_000_000)));
end Test_Monte_Carlo;
Task: Monte Carlo methods

C: #include <stdio.h>
#include <stdlib.h>
#include <math.h>
 
double pi(double tolerance)
{
	double x, y, val, error;
	unsigned long sampled = 0, hit = 0, i;

	do {
		
		for (i = 1000000; i; i--, sampled++) {
			x = rand() / (RAND_MAX + 1.0);
			y = rand() / (RAND_MAX + 1.0);
			if (x * x + y * y < 1) hit ++;
		}

		val = (double) hit / sampled;
		error = sqrt(val * (1 - val) / sampled) * 4;
		val *= 4;

		
		fprintf(stderr, "Pi = %f +/- %5.3e at %ldM samples.\r",
			val, error, sampled/1000000);
	} while (!hit || error > tolerance);
              

	return val;
}

int main()
{
	printf("Pi is %f\n", pi(3e-4)); 
	return 0;
}
Task: Monte Carlo methods



C#: using System;

class Program {
    static double MonteCarloPi(int n) {
        int inside = 0;
        Random r = new Random();

        for (int i = 0; i < n; i++) {
            if (Math.Pow(r.NextDouble(), 2)+ Math.Pow(r.NextDouble(), 2) <= 1) {
                inside++;
            }
        }

        return 4.0 * inside / n;
    }

    static void Main(string[] args) {
        int value = 1000;
        for (int n = 0; n < 5; n++) {
            value *= 10;
            Console.WriteLine("{0}:{1}", value.ToString("#,###").PadLeft(11, ' '), MonteCarloPi(value));
        }
    }
}
Task: Monte Carlo methods


C++: #include<iostream>
#include<math.h>
#include<stdlib.h>
#include<time.h>
 
using namespace std;
int main(){
    int jmax=1000; 
    int imax=1000; 
    double x,y;    
    int hit;       
    srand(time(0));
    for (int j=0;j<jmax;j++){
        hit=0;
        x=0; y=0;
        for(int i=0;i<imax;i++){
            x=double(rand())/double(RAND_MAX);
            y=double(rand())/double(RAND_MAX);
        if(y<=sqrt(1-pow(x,2))) hit+=1; }          
    cout<<""<<4*double(hit)/double(imax)<<endl; }  
}
Task: Monte Carlo methods





Java: public class MC {
	public static void main(String[] args) {
		System.out.println(getPi(10000));
		System.out.println(getPi(100000));
		System.out.println(getPi(1000000));
		System.out.println(getPi(10000000));
		System.out.println(getPi(100000000));
		
	}
	public static double getPi(int numThrows){
		int inCircle= 0;
		for(int i= 0;i < numThrows;i++){
			
			
			double randX= (Math.random() * 2) - 1;
			double randY= (Math.random() * 2) - 1;
			
			double dist= Math.sqrt(randX * randX + randY * randY);
			
			if(dist < 1){
				inCircle++;
			}
		}
		return 4.0 * inCircle / numThrows;
	}
}
Task: Monte Carlo methods







Python: >>> import random, math
>>> throws = 1000
>>> 4.0 * sum(math.hypot(*[random.random()*2-1
	                 for q in [0,1]]) < 1
              for p in xrange(throws)) / float(throws)
3.1520000000000001
>>> throws = 1000000
>>> 4.0 * sum(math.hypot(*[random.random()*2-1
	                 for q in [0,1]]) < 1
              for p in xrange(throws)) / float(throws)
3.1396359999999999
>>> throws = 100000000
>>> 4.0 * sum(math.hypot(*[random.random()*2-1
	                 for q in [0,1]]) < 1
              for p in xrange(throws)) / float(throws)
3.1415666400000002
Task: Monte Carlo methods




Go: package main

import (
    "fmt"
    "math"
    "math/rand"
    "time"
)

func getPi(numThrows int) float64 {
    inCircle := 0
    for i := 0; i < numThrows; i++ {
        
        
        randX := rand.Float64()*2 - 1 
        randY := rand.Float64()*2 - 1 
        
        dist := math.Hypot(randX, randY)
        if dist < 1 { 
            inCircle++
        }
    }
    return 4 * float64(inCircle) / float64(numThrows)
}

func main() {
    rand.Seed(time.Now().UnixNano())
    fmt.Println(getPi(10000))
    fmt.Println(getPi(100000))
    fmt.Println(getPi(1000000))
    fmt.Println(getPi(10000000))
    fmt.Println(getPi(100000000))
}
Task: Monte Carlo methods



C#: using System;

class Program {
    static double MonteCarloPi(int n) {
        int inside = 0;
        Random r = new Random();

        for (int i = 0; i < n; i++) {
            if (Math.Pow(r.NextDouble(), 2)+ Math.Pow(r.NextDouble(), 2) <= 1) {
                inside++;
            }
        }

        return 4.0 * inside / n;
    }

    static void Main(string[] args) {
        int value = 1000;
        for (int n = 0; n < 5; n++) {
            value *= 10;
            Console.WriteLine("{0}:{1}", value.ToString("#,###").PadLeft(11, ' '), MonteCarloPi(value));
        }
    }
}








Fortran: MODULE Simulation
 
   IMPLICIT NONE
 
   CONTAINS
 
   FUNCTION Pi(samples)
     REAL :: Pi
     REAL :: coords(2), length
     INTEGER :: i, in_circle, samples
  
     in_circle = 0
     DO i=1, samples
       CALL RANDOM_NUMBER(coords)
       coords = coords * 2 - 1
       length = SQRT(coords(1)*coords(1) + coords(2)*coords(2))
       IF (length <= 1) in_circle = in_circle + 1
     END DO
     Pi = 4.0 * REAL(in_circle) / REAL(samples)
   END FUNCTION Pi
 
 END MODULE Simulation
  
 PROGRAM MONTE_CARLO
 
   USE Simulation 
   
   INTEGER :: n = 10000
 
   DO WHILE (n <= 100000000)
     WRITE (*,*) n, Pi(n)
     n = n * 10
   END DO
     
 END PROGRAM MONTE_CARLO
Task: Monte Carlo methods


C++: #include<iostream>
#include<math.h>
#include<stdlib.h>
#include<time.h>
 
using namespace std;
int main(){
    int jmax=1000; 
    int imax=1000; 
    double x,y;    
    int hit;       
    srand(time(0));
    for (int j=0;j<jmax;j++){
        hit=0;
        x=0; y=0;
        for(int i=0;i<imax;i++){
            x=double(rand())/double(RAND_MAX);
            y=double(rand())/double(RAND_MAX);
        if(y<=sqrt(1-pow(x,2))) hit+=1; }          
    cout<<""<<4*double(hit)/double(imax)<<endl; }  
}









Fortran: MODULE Simulation
 
   IMPLICIT NONE
 
   CONTAINS
 
   FUNCTION Pi(samples)
     REAL :: Pi
     REAL :: coords(2), length
     INTEGER :: i, in_circle, samples
  
     in_circle = 0
     DO i=1, samples
       CALL RANDOM_NUMBER(coords)
       coords = coords * 2 - 1
       length = SQRT(coords(1)*coords(1) + coords(2)*coords(2))
       IF (length <= 1) in_circle = in_circle + 1
     END DO
     Pi = 4.0 * REAL(in_circle) / REAL(samples)
   END FUNCTION Pi
 
 END MODULE Simulation
  
 PROGRAM MONTE_CARLO
 
   USE Simulation 
   
   INTEGER :: n = 10000
 
   DO WHILE (n <= 100000000)
     WRITE (*,*) n, Pi(n)
     n = n * 10
   END DO
     
 END PROGRAM MONTE_CARLO
Task: Monte Carlo methods

C: #include <stdio.h>
#include <stdlib.h>
#include <math.h>
 
double pi(double tolerance)
{
	double x, y, val, error;
	unsigned long sampled = 0, hit = 0, i;

	do {
		
		for (i = 1000000; i; i--, sampled++) {
			x = rand() / (RAND_MAX + 1.0);
			y = rand() / (RAND_MAX + 1.0);
			if (x * x + y * y < 1) hit ++;
		}

		val = (double) hit / sampled;
		error = sqrt(val * (1 - val) / sampled) * 4;
		val *= 4;

		
		fprintf(stderr, "Pi = %f +/- %5.3e at %ldM samples.\r",
			val, error, sampled/1000000);
	} while (!hit || error > tolerance);
              

	return val;
}

int main()
{
	printf("Pi is %f\n", pi(3e-4)); 
	return 0;
}










Fortran: MODULE Simulation
 
   IMPLICIT NONE
 
   CONTAINS
 
   FUNCTION Pi(samples)
     REAL :: Pi
     REAL :: coords(2), length
     INTEGER :: i, in_circle, samples
  
     in_circle = 0
     DO i=1, samples
       CALL RANDOM_NUMBER(coords)
       coords = coords * 2 - 1
       length = SQRT(coords(1)*coords(1) + coords(2)*coords(2))
       IF (length <= 1) in_circle = in_circle + 1
     END DO
     Pi = 4.0 * REAL(in_circle) / REAL(samples)
   END FUNCTION Pi
 
 END MODULE Simulation
  
 PROGRAM MONTE_CARLO
 
   USE Simulation 
   
   INTEGER :: n = 10000
 
   DO WHILE (n <= 100000000)
     WRITE (*,*) n, Pi(n)
     n = n * 10
   END DO
     
 END PROGRAM MONTE_CARLO
Task: Monte Carlo methods





Java: public class MC {
	public static void main(String[] args) {
		System.out.println(getPi(10000));
		System.out.println(getPi(100000));
		System.out.println(getPi(1000000));
		System.out.println(getPi(10000000));
		System.out.println(getPi(100000000));
		
	}
	public static double getPi(int numThrows){
		int inCircle= 0;
		for(int i= 0;i < numThrows;i++){
			
			
			double randX= (Math.random() * 2) - 1;
			double randY= (Math.random() * 2) - 1;
			
			double dist= Math.sqrt(randX * randX + randY * randY);
			
			if(dist < 1){
				inCircle++;
			}
		}
		return 4.0 * inCircle / numThrows;
	}
}






Fortran: MODULE Simulation
 
   IMPLICIT NONE
 
   CONTAINS
 
   FUNCTION Pi(samples)
     REAL :: Pi
     REAL :: coords(2), length
     INTEGER :: i, in_circle, samples
  
     in_circle = 0
     DO i=1, samples
       CALL RANDOM_NUMBER(coords)
       coords = coords * 2 - 1
       length = SQRT(coords(1)*coords(1) + coords(2)*coords(2))
       IF (length <= 1) in_circle = in_circle + 1
     END DO
     Pi = 4.0 * REAL(in_circle) / REAL(samples)
   END FUNCTION Pi
 
 END MODULE Simulation
  
 PROGRAM MONTE_CARLO
 
   USE Simulation 
   
   INTEGER :: n = 10000
 
   DO WHILE (n <= 100000000)
     WRITE (*,*) n, Pi(n)
     n = n * 10
   END DO
     
 END PROGRAM MONTE_CARLO
Task: Monte Carlo methods







Python: >>> import random, math
>>> throws = 1000
>>> 4.0 * sum(math.hypot(*[random.random()*2-1
	                 for q in [0,1]]) < 1
              for p in xrange(throws)) / float(throws)
3.1520000000000001
>>> throws = 1000000
>>> 4.0 * sum(math.hypot(*[random.random()*2-1
	                 for q in [0,1]]) < 1
              for p in xrange(throws)) / float(throws)
3.1396359999999999
>>> throws = 100000000
>>> 4.0 * sum(math.hypot(*[random.random()*2-1
	                 for q in [0,1]]) < 1
              for p in xrange(throws)) / float(throws)
3.1415666400000002




Fortran: MODULE Simulation
 
   IMPLICIT NONE
 
   CONTAINS
 
   FUNCTION Pi(samples)
     REAL :: Pi
     REAL :: coords(2), length
     INTEGER :: i, in_circle, samples
  
     in_circle = 0
     DO i=1, samples
       CALL RANDOM_NUMBER(coords)
       coords = coords * 2 - 1
       length = SQRT(coords(1)*coords(1) + coords(2)*coords(2))
       IF (length <= 1) in_circle = in_circle + 1
     END DO
     Pi = 4.0 * REAL(in_circle) / REAL(samples)
   END FUNCTION Pi
 
 END MODULE Simulation
  
 PROGRAM MONTE_CARLO
 
   USE Simulation 
   
   INTEGER :: n = 10000
 
   DO WHILE (n <= 100000000)
     WRITE (*,*) n, Pi(n)
     n = n * 10
   END DO
     
 END PROGRAM MONTE_CARLO
Task: Monte Carlo methods






PHP: <?
$loop = 1000000; # loop to 1,000,000
$count = 0;
for ($i=0; $i<$loop; $i++) {
  $x = rand() / getrandmax();
  $y = rand() / getrandmax();
  if(($x*$x) + ($y*$y)<=1) $count++;
}
echo "loop=".number_format($loop).", count=".number_format($count).", pi=".($count/$loop*4);
?>





Fortran: MODULE Simulation
 
   IMPLICIT NONE
 
   CONTAINS
 
   FUNCTION Pi(samples)
     REAL :: Pi
     REAL :: coords(2), length
     INTEGER :: i, in_circle, samples
  
     in_circle = 0
     DO i=1, samples
       CALL RANDOM_NUMBER(coords)
       coords = coords * 2 - 1
       length = SQRT(coords(1)*coords(1) + coords(2)*coords(2))
       IF (length <= 1) in_circle = in_circle + 1
     END DO
     Pi = 4.0 * REAL(in_circle) / REAL(samples)
   END FUNCTION Pi
 
 END MODULE Simulation
  
 PROGRAM MONTE_CARLO
 
   USE Simulation 
   
   INTEGER :: n = 10000
 
   DO WHILE (n <= 100000000)
     WRITE (*,*) n, Pi(n)
     n = n * 10
   END DO
     
 END PROGRAM MONTE_CARLO
Task: Monte Carlo methods






PHP: <?
$loop = 1000000; # loop to 1,000,000
$count = 0;
for ($i=0; $i<$loop; $i++) {
  $x = rand() / getrandmax();
  $y = rand() / getrandmax();
  if(($x*$x) + ($y*$y)<=1) $count++;
}
echo "loop=".number_format($loop).", count=".number_format($count).", pi=".($count/$loop*4);
?>