jodawill
08-29-2011, 03:27 PM
I'm trying to write a pi calculator that shows a comparison of the calculated value to the actual value. It works, but the output of the comparison shows only the first two decimal spots, followed by two 9s.
Why is it showing two 9s and how can I make it more precise?
<head>
<title>
Pi Calculator
</title>
<script language="JavaScript">
function calcpi(digitsn) {
p = 1;
s = 0;
for (c = 3; c < digitsn; c += 2) {
if (s == 0) {
p -= 1/c;
s = 1;
} else {
p += 1/c;
s = 0;
}
}
p *= 4;
return p;
}
function hid(input) { //Highlight Incorrect Digits
pi = "3.14159265358979323846".split('');
input = input.toString().split('');
result = "";
for (c = 0; c < input.length; c++) {
if (input[c] != pi[c]) {
//result += "; " + input[c] + "!=" + pi[c];
result += "<span style='background-color:red'>" + input[c] + "</span>";
} else {
result += input[c];
}
}
return result;
}
</script>
</head>
<body>
Repeat algorithm x many times:<br/>
<input type="text" value="10000" id="digitsx"/><br/>
<input type="button" onClick="document.getElementById('answer').value=calcpi(parseInt(document.getElementById('digitsx').value)).t oString()" value="Calculate"/><br/>
Result:<br/>
<input type="text" readonly id="answer"/><br/>
Correct value:<br/>
<input type="text" readonly value="3.14159265358979323846"/><br/>
<input type="button" value="Compare" onClick="document.getElementById('comparison').innerHTML = hid('3.1499')"/>
<div id="comparison"/>
</body>
Why is it showing two 9s and how can I make it more precise?
<head>
<title>
Pi Calculator
</title>
<script language="JavaScript">
function calcpi(digitsn) {
p = 1;
s = 0;
for (c = 3; c < digitsn; c += 2) {
if (s == 0) {
p -= 1/c;
s = 1;
} else {
p += 1/c;
s = 0;
}
}
p *= 4;
return p;
}
function hid(input) { //Highlight Incorrect Digits
pi = "3.14159265358979323846".split('');
input = input.toString().split('');
result = "";
for (c = 0; c < input.length; c++) {
if (input[c] != pi[c]) {
//result += "; " + input[c] + "!=" + pi[c];
result += "<span style='background-color:red'>" + input[c] + "</span>";
} else {
result += input[c];
}
}
return result;
}
</script>
</head>
<body>
Repeat algorithm x many times:<br/>
<input type="text" value="10000" id="digitsx"/><br/>
<input type="button" onClick="document.getElementById('answer').value=calcpi(parseInt(document.getElementById('digitsx').value)).t oString()" value="Calculate"/><br/>
Result:<br/>
<input type="text" readonly id="answer"/><br/>
Correct value:<br/>
<input type="text" readonly value="3.14159265358979323846"/><br/>
<input type="button" value="Compare" onClick="document.getElementById('comparison').innerHTML = hid('3.1499')"/>
<div id="comparison"/>
</body>