Skip to content

Instantly share code, notes, and snippets.

@mattcodez
Last active September 11, 2017 02:21
Show Gist options
  • Save mattcodez/38ff40ac307b83c0fca5cf220418f2e7 to your computer and use it in GitHub Desktop.
Save mattcodez/38ff40ac307b83c0fca5cf220418f2e7 to your computer and use it in GitHub Desktop.
Very simple JS pi generator
// g++ -o mypi -std=c++14 mypi.cpp
#include <iostream>
#include <string>
#include <ctime>
#include <limits>
double myPi(long long loopCount);
typedef std::numeric_limits< double > dbl;
int main(int argc, char *argv[])
{
using namespace std;
long long loopCount = 602;
if (argc >= 2) loopCount = strtoll(argv[1], NULL, 10);
cout << "loopCount: " + to_string(loopCount) << endl;
clock_t begin = clock();
double pi = myPi(loopCount);
clock_t end = clock();
double elapsed_secs = double(end - begin) / CLOCKS_PER_SEC;
cout.precision(dbl::max_digits10);
cout << "Pi: " << fixed << pi << endl;
cout << "Time(s): " + to_string(elapsed_secs) << endl;
}
double myPi(long long loopCount){
double pi = 1.0;
bool flag = false;
//600 gives about 2 decimal accuracy, increase for more
for (long long i = 3; i < loopCount; i+=2){
if (flag) {
pi += (1.0/i);
flag = false;
}
else {
pi -= (1.0/i);
flag = true;
}
}
return (pi * 4);
}
let pi = 1, flag = false;
//600 gives about 2 decimal accuracy, increase for more
for (let i = 3; i < 600; i+=2){
if (flag) {
pi += (1/i);
flag = false;
}
else {
pi -= (1/i);
flag = true;
}
}
console.log(pi * 4);
let myPi;
fetch('https://rawgit.com/mattcodez/junk/master/pi.wasm')
.then((res,err) => {
if (res.type === 'opaque' || res.ok)
return res.arrayBuffer();
else {
console.log('res', res);
throw new Error(`Unable to fetch WASM.`);
}
})
.then(bytes => {//console.log('bytes', bytes);
return WebAssembly.compile(bytes);
})
.then(module => {
return WebAssembly.instantiate(module);
})
.then(instance => {
myPi = instance.exports._Z4myPiv;
//console.log(instance.exports)
let start = Date.now();
console.log('pi', 4 * myPi());
let total = Date.now() - start;
console.log(`ran in ${total} seconds`);
})
.catch(e => console.log(e));
//same as pi.js but with web workers so that we don't lock the browser
//on long processes
let blob = new Blob([`
let pi = 1, flag = false;
for (let i = 3; i < 600000000; i+=2){
if (flag) {
pi += (1/i);
flag = false;
}
else {
pi -= (1/i);
flag = true;
}
}
postMessage(pi * 4);
`], { type: "text/javascript" });
let worker = new Worker(window.URL.createObjectURL(blob));
let start = Date.now();
worker.onmessage = function (e){
let time = Date.now() - start;
console.log(`pi in ${time} seconds:`, e.data)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment