I figured out an equation for finding digits of pi, and it seems to work fine with the for loop, but I was wondering if there was a way to reduce the 12 variables. The point of them is to increase the accuracy of the approximation, but there is a lot of them. I need a way to still have the functionality of the twelve variables, but written with less code.
Here is the full code:
function approximatePi() {
//Get P element
var t = document.getElementById("t")
//For loop
for (let i = 0; i < 1000; i ) {
//Variable for number close to pi//
var a = 3.14
//Math
var a2 = a Math.sin(a)
var a3 = a2 Math.sin(a2)
var a4 = a3 Math.sin(a3)
var a5 = a4 Math.sin(a4)
var a6 = a5 Math.sin(a5)
var a7 = a6 Math.sin(a6)
var a8 = a7 Math.sin(a7)
var a9 = a8 Math.sin(a8)
var a10 = a9 Math.sin(a9)
var a11 = a10 Math.sin(a10)
var a12 = a11 Math.sin(a11)
var a13 = a12 Math.sin(a12)
var a14 = a13 Math.sin(a13)
var a15 = a14 Math.sin(a14)
t.innerText = parseFloat(a12).toPrecision(50)
}
}
CodePudding user response:
You are repeating the same operation multiple times and printing the result after 12 steps. That can be simplified with a loop:
function approximatePi() {
//Get P element
var t = document.getElementById("t")
//For loop
for (let i = 0; i < 1000; i ) {
//Variable for number close to pi//
var a = 3.14
//Math
for (let j = 0; j < 12; j) a = a Math.sin(a);
t.innerText = parseFloat(a).toPrecision(50)
}
}
If you need all the results, use an array:
function approximatePi() {
//Get P element
var t = document.getElementById("t")
//For loop
for (let i = 0; i < 1000; i ) {
//Variable for number close to pi//
var a = [3.14]
//Math
for (let j = 1; j <= 12; j) a[j] = a[j-1] Math.sin(a[i-1]);
t.innerText = parseFloat(a[12]).toPrecision(50)
}
}
CodePudding user response:
This could work. Although, I am not 100 percent sure what the question is asking for. Could you type the question.
function approximatePi(){
var t = document.getElementById("t");
var a =[];
a[0] = 3.14;
for(var i = 1; i<1000; i ){
a[i] = a[i-1] Math.sin(a[i-1]);
}
console.log(a[1]);
}
approximatePi();