...

View Full Version : Decimal precision in strings



jodawill
08-29-2011, 04: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>

devnull69
08-29-2011, 05:42 PM
What? But you are directly telling it to compare 3.1499 and not the actual result. Therefore it cannot be any more precise.

Change this line


<input type="button" value="Compare" onClick="document.getElementById('comparison').innerHTML = hid('3.1499')"/>


to that


<input type="button" value="Compare" onClick="document.getElementById('comparison').innerHTML = hid(document.getElementById('answer').value)"/>

jodawill
08-29-2011, 06:06 PM
What? But you are directly telling it to compare 3.1499 and not the actual result. Therefore it cannot be any more precise.

Change this line


<input type="button" value="Compare" onClick="document.getElementById('comparison').innerHTML = hid('3.1499')"/>


to that


<input type="button" value="Compare" onClick="document.getElementById('comparison').innerHTML = hid(document.getElementById('answer').value)"/>


Oh gosh... how embarrassing! I forgot I put that there when I was just screwing around. Thanks for pointing out my stupidity :)



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum