Estimating Pi in Javascript

Asked

Viewed 33 times

-3

I’m trying to estimate Pi, but I get one NaN.

var x = 0
var y = 0
var fora = 0
var dentro = 0
var f = document.querySelector('input#t')
var t = Number(f.value)
var pi = document.querySelector('div#pi')
var atual = 0
var distance = 0

function start() {
  while (atual < t) {
    x = Math.random()
    y = Math.random()
    distance = x ** 2 + y ** 2
    if (distance <= 1) {
      dentro += 1
      atual += 1
    } else {
      fora += 1
      atual += 1

    }
  }
  pi.innerHTML = 4 * dentro / fora
}
<h1>Calculador de pi</h1>
<p>Insira um número de tentavicas</p><input type="number" name="t" id="t"><input type="button" value="start" onclick="start()">
<div id="pi">asdas</div>

  • 4*dentro/fora if you never increment the value of "outside" will be a division by zero, pq the variable is started like this var fora = 0, should start with 1, which is a "neutral" value in the

1 answer

0


Some errors present in your code:

  • start the variable t out of function start. In this case, the variable will be executed when the HTML is created, and in this step, the value of the text box is empty, causing f.value be it '' and Number('') be it NaN.

  • dividing dentro for fora instead of atual.

You can fix them that way:

var f = document.querySelector('input#t')
var pi = document.querySelector('div#pi')

function start() {
  var x = 0
  var y = 0
  var fora = 0
  var dentro = 0
  var atual = 0
  var distance = 0
  var t = parseInt(f.value)

  while (atual < t) {
    x = Math.random()
    y = Math.random()
    distance = x ** 2 + y ** 2
    if (distance <= 1) {
      dentro += 1
      atual += 1
    } else {
      fora += 1
      atual += 1
    }
  }
  pi.innerHTML = 4 * dentro / atual
}
<h1>Calculador de pi</h1>
<p>Insira um número de tentavicas</p><input type="number" name="t" id="t"><input type="button" value="start" onclick="start()">
<div id="pi">asdas</div>

  • 1

    Actually, I had put the value of F as the input when it was actually supposed to be the current E on the value outside the function was really what Nan was giving. Thank you so much for your help, now I can continue my studies ! (:

Browser other questions tagged

You are not signed in. Login or sign up in order to post.