假設我有一個名為 bars() 的函式
bars () {
const bars = []
for (let i = 0; i < this.numberOfBars; i ) {
bars.push(Math.sqrt(this.numberOfBars * this.numberOfBars - i * i))
}
return bars
}
如果我將 bars 陣列減少到近似 PI,箭頭函式的右側應該是什么?
PI = bars().reduce((a, b) =>
我嘗試將這些值相加并除以條數,但我并沒有接近 Pi 的近似值。我覺得我缺少一個簡單的技巧。
uj5u.com熱心網友回復:
你的函式似乎列出了四分之一圓中“條形”的長度,所以我們必須將它們全部加起來(得到四分之一圓的面積),然后乘以 4(因為有 4 個四分之一)和除以this.numberOfBars^ 2 因為area = π * r^2,但就像我們必須知道半徑一樣,最好使用純函式:
// Your function rewritten as a pure one
const bars = numberOfBars => {
const bars = []
for (let i = 0; i < numberOfBars; i ) {
bars.push(Math.sqrt(numberOfBars * numberOfBars - i * i))
}
return bars
}
// Here we take 1000 bars as an example but in your case you replace it by this.numberOfBars
// Sum them all up, multiply by 4, divide by the square of the radius
const PI = bars(1000).reduce((g, c) => g c) * 4 / Math.pow(1000, 2)
console.log(PI)
uj5u.com熱心網友回復:
/** Approximates PI using geometry
* You get a better approximation using more bars and a smaller step size
*/
function approximatePI(numberOfBars, stepSize) {
const radius = numberOfBars * stepSize;
// Generate bars (areas of points on quarter circle)
let bars = [];
// You can think of i as some point along the x-axis
for (let i = 0; i < radius; i = stepSize) {
let height = Math.sqrt(radius*radius - i*i)
bars.push(height * stepSize);
}
// Add up all the areas of the bars
// (This is approximately the area of a quarter circle if stepSize is small enough)
const quarterArea = bars.reduce((a, b) => a b);
// Calculate PI using area of circle formula
const PI = 4 * quarterArea / (radius*radius)
return PI;
}
console.log(`PI is approximately ${approximatePI(100_000, 0.001)}`);
uj5u.com熱心網友回復:
沒有理由將所有項都推入一個陣列,然后通過加法來減少陣列。只需使用一個累加器變數并將所有項添加到它。
請注意,越接近半徑的末端,計算的準確性就會越來越差。如果求和為半徑的一半,則得到 r2(3√3 π)/24,從中可以得出 π。
(盡管無論如何,這是評估 π 的最差方法之一。)
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/535660.html
標籤:javascript数学
