-4

I have a precision problem in C++. I have two angles which their average is pi/2 and they are like pi/2 +- alpha so the absolute values of sine and cosine should be equal. When I find their sine values in MATLAB they are equal, which they should be. Try out : sin(1.25911) & sin(1.88252) and their sum is 3.1416. But when I find these values in C++ the answer is : 0.951818 and 0.951806

How can I increase the accuracy of these numbers so the get equal? I can choose my precision up to 3 decimal numbers but I prefer to keep it up to 6.

ivan_pozdeev
  • 33,874
  • 19
  • 107
  • 152
aaa
  • 161
  • 1
  • 1
  • 8
  • In MATLAB, type `format long`, then repeat your experiment: `sin(1.25911)` is `0.951817787502636`, `sin(1.88252)` is `0.951806334033813`. Rounded to 6 values after the comma, this is the same as your C++ answer. The difference you see is because you're looking at rounded values to different precision. – Cris Luengo Aug 27 '18 at 06:07
  • Possible duplicate of [sin, cos, tan and rounding error](https://stackoverflow.com/questions/1527588/sin-cos-tan-and-rounding-error) – ivan_pozdeev Aug 27 '18 at 18:40

1 Answers1

1

3.1416 is a crude approximation to pi. If you use a better value, you'll get a better answer from sin. So,

sin(1.25911)=0.951817787502636
sin(pi-1.25911)=sin(1.88248265358979)=0.951817787502636

Note, that I've used more accurate input values to sin here, their average is closer to pi/2 than your example.

geza
  • 28,403
  • 6
  • 61
  • 135
  • Hi Thanks for your answer. The problem is that I don't have control over those numbers. Actually, it's simulation and there are sometimes that those numbers appear in my simulation and their sum supposed to be about pi but it doesn't due to my limited precision. – aaa Aug 27 '18 at 16:41
  • 1
    @aaa: I don't understand your intent then. If the inputs are already inaccurate, why do you expect that the output will be accurate? – geza Aug 27 '18 at 17:11
  • @aaa You should probably calculate precision alongside the actual calculations. – ivan_pozdeev Aug 27 '18 at 18:45
  • @geza because Matlab gives me an accurate(at least equal) answer for those numbers. – aaa Aug 30 '18 at 19:00
  • @aaa [round them to 4 fractional digits](https://stackoverflow.com/questions/9849535/how-to-round-a-double-to-n-decimals) if that makes you feel better. This is the precision that MATLAB gives you in your examples. – ivan_pozdeev Aug 31 '18 at 05:12