Last active
August 30, 2023 14:46
-
-
Save gollilla/7004948ba286e4954ec9c1167db31f8d to your computer and use it in GitHub Desktop.
Parallelを使ってモンテカルロを並列計算
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
const N = 100000000; | |
$para_count = 12; | |
$parallel = new ParallelFor(function(int $c){ | |
$x = mt_rand() / mt_getrandmax(); | |
$y = mt_rand() / mt_getrandmax(); | |
if(($x**2 + $y**2)**2 < 1) $c++; | |
return $c; | |
}, N, $para_count); | |
$c = 0; | |
for($i=0;$i<$para_count;$i++){ | |
$c += $parallel->getFutures()[$i]->value(); | |
} | |
$pi = 4*$c/N; | |
var_dump($pi); | |
class ParallelFor { | |
public function __construct(Closure $func, int $count, int $max_parallel){ | |
$this->func = $func; | |
if($count < $max_parallel){ | |
echo 'count < max_parallel', PHP_EOL; | |
return; | |
} | |
$this->count = $count; | |
$this->max_parallel = $max_parallel; | |
$futures = []; | |
for($i=0;$i<$max_parallel;$i++){ | |
$runtime = ParallelFactory::create(); | |
$futures[] = $runtime->run(function() use ($func, $i, $count, $max_parallel){ | |
$c = 0; | |
for($j=($count/$max_parallel)*$i;$j<($count/$max_parallel)*($i+1);$j++){ | |
$c = ($func)($c); | |
} | |
return $c; | |
}); | |
} | |
$this->futures = $futures; | |
} | |
public function getFunction(){ | |
return $this->func; | |
} | |
public function getFutures(){ | |
return $this->futures; | |
} | |
public function getMaxParallel(){ | |
return $this->max_parallel; | |
} | |
} | |
class ParallelFactory { | |
public static function create(){ | |
return new \parallel\Runtime; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
汎用性のある書き方を見つけたい