-1

I am working on a javascript code which calculates the value of Pi. So here's the problem. When eval() calculates the string which is generated by the code it returns 1. It is supposed to return 1.49138888889 (which is a rough value of Pi^2/6).

Here's the code. It returns the correct calculation as a string, But eval() doesn't calculate it properly.

function calculate() {
  var times = 10;
  var functionpart1 = "1/";
  var functionpart2 = "^2+";
  var x;
  for (var functionpistring = "", x = 1; times != 0; times--, x++) {
    functionpistring = functionpistring + functionpart1 + x.toString() + functionpart2;
  }
  document.getElementById("value").innerHTML = eval(functionpistring.slice(0, functionpistring.length - 1));
}
cch
  • 3,336
  • 8
  • 33
  • 61
Somebody
  • 333
  • 3
  • 12
  • 6
    I suspect you are confusing [XOR](http://stackoverflow.com/questions/3618340/javascript-what-does-the-caret-operator-do) with [pow](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/pow). – Quentin Jun 21 '15 at 15:38
  • 1
    Why are you doing this? –  Jun 21 '15 at 15:39
  • I actually got it to calculate perfectly now that I used Math.pow() – Somebody Jun 21 '15 at 16:11

1 Answers1

0
function calculate() {
    var times = 20, // max loops
        x,          // counter
        f = 0,      // value representation
        s = '';     // string representation
    function square(x) {
        return x * x;
    }
    function inv(x) {
        return 1 / x;
    }
    function squareS(x) {
        return x + '²';
    }
    function invS(x) {
        return '1 / ' + x;
    }
    for (x = 0; x < times; x++) {
        f += square(inv(x));
        s += (s.length ? ' + ' : '') + squareS(invS(x));
        document.write(f + ' = ' + s);
    }
}
calculate();
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392