A calculator program I have created works almost perfectly with the exception that Math.Sin() and Math.Log() seem to have some inaccuracies that I can't seem to get to the bottom of. I will try give as much detail as I can.
Math.Sin() Problem:
First, this is NOT a radian problem (at least so far as I can tell). Numbers are fed to Math.Sin() as double. It works for some values in both degrees and radians but not for others like 180 and pi respectively. Now for some code:
private void buttonSin_Click(object sender, EventArgs e)
{
if (radioDeg.Checked)
{
firstOperand = Math.PI/180*firstOperand;
}
firstOperand = Math.Sin(firstOperand);
secondOperand = 0;
displayScreen.Text = firstOperand.ToString();
clickCount = 0;
operationCount++;
}
firstOperand is double and is (along with secondOperand) used for subsequent calculations that would take place. I think other parts of the code are self-explanatory but I'll be happy to elaborate if necessary. Math.Sin(Math.PI)=1.224... instead of 0 as it should. However Math.Sin(Math.PI/4)=0.707... as expected. Furthermore, this is only when pi is generated as Math.PI. If entered in manually as 3.14159, Math.Sin()=2.65... If entered in as 3.1415926 I get Math.Sin()=5.35... Can anyone point out why?
Math.Log() Problem:
This part works almost perfectly. The only error occurs when the function is applied successively. Take a look at the code:
private void buttonLn_Click(object sender, EventArgs e)
{
firstOperand = Math.Log(firstOperand);
secondOperand = 0;
displayScreen.Text = firstOperand.ToString();
clickCount = 0;
operationCount++;
}
Math.Log(Math.E)=1 as it should, but when the ln button is hit immediately thereafter, I get a value of 1.776... Note that if 2.718 is entered in manually and then the ln button is hit twice in succession, I get -.0001... which is much closer to the actual answer of 0.
I'm sorry if these should be separate posts, but I thought both problems might relate to how constants Math.PI and Math.E are handled. Any thoughts?
Check your exponents. When I evaluate Math.Sin(Math.Pi) here in VS 2010 debug evaluator, I see this: 0.00000000000000012246063538223773
That would be output as 1.224e-16.
Either way, it's just a hair's breadth from zero. As with many floating point operations, close enough should be considered zero.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With