C # Math.Sin () and Math.Log () Inaccuracies

The calculator program I created works almost perfectly, except that Math.Sin () and Math.Log () seem to have some inaccuracies that I seem to be unable to understand. I will try to give as many details as possible.

Task Math.Sin ():

Firstly, this is NOT a RADIAN problem (at least as far as I can tell). Numbers are given in Math.Sin () as doubles. It works for some values ​​in both degrees and radians, but not for others, such as 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 the second statement) used for subsequent calculations that will take place. I think that other parts of the code do not require explanation, but I will be happy to clarify 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 only happens when pi is generated as Math.PI. If entered manually as 3.14159, Math.Sin () = 2.65 ... If entered as 3.1415926, I get Math.Sin () = 5.35 ... Can someone please indicate why?

Math.Log () error:

This part works almost perfectly. The only error occurs when a function is applied sequentially. 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 immediately hits, I get the value 1.776 ... Please note that if 2.718 is entered manually, and then the ln button two times in a row I get - .0001 ... which is much closer to the actual answer 0.

I am sorry if they should be separate messages, but I thought that both problems could be related to the way the Math.PI and Math.E constants are handled. Any thoughts?

+4
source share
3 answers

Check your performance. When I evaluate Math.Sin (Math.Pi) here in the VS 2010 debugging evaluator, I see the following: 0.00000000000000012246063538223773

This will be output as 1.224e-16.

In any case, it's just the width of the hair from scratch. As with many floating point operations, it is fairly close to being considered zero.

+9
source

Math.Sin(Math.PI) => 1.2246063538223773e-16 , which is pretty much 0, not 1.224

I suspect the same goes for your Log(e) code.

+6
source

Math.Sin (Math.PI) = 1.224 ... instead of 0, as it should be

This is not actually 1.224, but 1.22460635382238E-16, which is almost but not quite zero.

+1
source

Source: https://habr.com/ru/post/1393022/


All Articles