0
Exercise
Hello to everyone, i got this exercise to solve but i dont know how i can do it, can anyone help me out on that? Exercise requires you to implement an HTML page that uses a function in Javascript which approximates the value of pi. The proposed method requires calculating the integral 4 / (1 + x * x) in the interval from -1/2 to 1 / 2. The method divides the above space into n segments, where for each segment the integral is approximated by the expression (1 / n) * (4 / (1 + x * x)). The page has a form with an input where the user sets the value of n and a key that calls the function with the parameter n. The function of updating text on the web page with the value of the pi calculated.
2 ответов
0
From where did you got this exercise?
Trying to resolve it, seems that computing integral (so even approximating) 4/(1+x*x) in the interval from -1/2 to 1/2 doesn't reach PI as limit ^^
Better way to compute (or approximate) integral of Math.sqrt(1-x*x) in the interval from -1 to 1, wich is half of unit circle area (PI/2):
function getpi(n) {
var p, m, x;
if (n<1) p = ''; // compute and display PI only if n >= 1
else {
p = 0;
m = 1/n;
x = -1+m/2; // approximate average of segment area with x at middle of each segment
while (x<1) {
p += m*Math.sqrt(1-x*x);
x += m;
}
p *= 2;
}
document.getElementById('pi').innerHTML = p;
}
... use it as:
<input type="number" oninput="getpi(this.value);">
0
A friend asked me to post this and get the solution. Thanks :)