這個演算法是如何作業的:它首先為一個點生成隨機坐標。然后它找到每個點到圓中心的距離。如果距離 <= 1,則該點在圓內,否則在圓外。圓中的點數與總點數的比值接近于 pi。
我想讓這個演算法運行得更快。我該怎么做?
function calc(iterations) {
pointCircle = 0, total = 0, x = 0, y = 0, distance = 0, pi = 0;
for (let i = 0; i < iterations; i ) {
x = Math.random().toFixed(1);
y = Math.random().toFixed(1);
distance = Math.sqrt(x * x y * y);
if (distance <= 1) {pointCircle ;}total ;
}
pi = 4 * (pointCircle / total); console.log(pi);
}
uj5u.com熱心網友回復:
這.toFixed(1)使得計算更加不準確,并且消耗了大量的 CPU 時間,至少在 V8 上是這樣。去掉它,給定數量的(大)迭代所需的時間似乎減少了大約 8 倍。
// Original code
function calc(iterations) {
pointCircle = 0, total = 0, x = 0, y = 0, distance = 0, pi = 0;
for (let i = 0; i < iterations; i ) {
x = Math.random().toFixed(1);
y = Math.random().toFixed(1);
distance = Math.sqrt(x * x y * y);
if (distance <= 1) {pointCircle ;}total ;
}
pi = 4 * (pointCircle / total); console.log('pi', pi);
}
setTimeout(() => {
const t0 = performance.now();
calc(1000000)
console.log('time', performance.now() - t0);
}, 2000);
// Modified code
function calc(iterations) {
pointCircle = 0, total = 0, x = 0, y = 0, distance = 0, pi = 0;
for (let i = 0; i < iterations; i ) {
x = Math.random();
y = Math.random();
distance = Math.sqrt(x * x y * y);
if (distance <= 1) {pointCircle ;}total ;
}
pi = 4 * (pointCircle / total); console.log('pi', pi);
}
setTimeout(() => {
const t0 = performance.now();
calc(1000000)
console.log('time', performance.now() - t0);
}, 2000);
另一個改進可以通過適當地確定變數的范圍來實作,而不是重新分配window物件的屬性,這看起來可以將 V8 上的速度進一步提高約 3 倍。
// Modified code 2
function calc(iterations) {
let total = 0;
let pointCircle = 0;
for (let i = 0; i < iterations; i ) {
const x = Math.random();
const y = Math.random();
if (Math.sqrt(x * x y * y) <= 1) { pointCircle ; }
total ;
}
const pi = 4 * (pointCircle / total); console.log('pi', pi);
}
setTimeout(() => {
const t0 = performance.now();
calc(1000000)
console.log('time', performance.now() - t0);
}, 2000);
謝謝btilly,Math.sqrt也不需要。
畢竟,當且僅當原始數字為時,sqrt 小于 1。
這剃掉了一點。
// Modified code 2
function calc(iterations) {
let total = 0;
let pointCircle = 0;
for (let i = 0; i < iterations; i ) {
const x = Math.random();
const y = Math.random();
if (x * x y * y <= 1) { pointCircle ; }
total ;
}
const pi = 4 * (pointCircle / total); console.log('pi', pi);
}
setTimeout(() => {
const t0 = performance.now();
calc(1000000)
console.log('time', performance.now() - t0);
}, 2000);
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/503671.html
標籤:javascript 算法
上一篇:Could not start SASL: b'Error in sasl_client_start (-4) SASL(-4)
