0

I keep getting the incorrect result for a cos function (I checked with both radians and degrees) given a = π, b = π/2, I'm trying to find cos(a+b), for which the correct result should be 0.

enter image description here

Below is the code I used

a = math.pi
b = math.pi/2
print(math.cos(a + b)) // result is -1.8369701987210297e-16

c = math.radians(math.pi)
d = math.radians(math.pi/2)
print(math.cos(c + d)) // result is 0.996619646078697

NSCoder
  • 1,594
  • 5
  • 25
  • 47
  • 1
    -1.8369701987210297e-16 is very close to 0 and 0.996619646078697 is close to 1. pi can't be exactly represented in any integer base with finite precision, therefore you can't get the exact result in any languages without symbolic math – phuclv Nov 02 '19 at 05:20
  • [weird answer to sin and cos of pi in python](https://stackoverflow.com/q/45214903/995714), [Sin and Cos function incorrect in python](https://stackoverflow.com/q/28780695/995714), [Why is incorrect value of pi output?](https://stackoverflow.com/q/55801898/995714), [Sin and Cos give unexpected results for well-known angles](https://stackoverflow.com/q/31502120/995714), [Value of sine 180 is coming out as 1.22465e-16](https://stackoverflow.com/q/6566512/995714) – phuclv Nov 02 '19 at 05:22
  • @phuclv yes, it does. I wanted to mark your answer as correct. Please fill it in the answer section so I could do so. – NSCoder Nov 02 '19 at 07:18
  • 1
    @NSCoder In your second example, you convert radians to radians, not degrees. The conversion then makes returns angles that are not related at all with your test. Thus, you get totally nonsense result (0.9966). And even if you converted the angles to degrees properly using `math.degrees(math.pi)`, you would not get the correct result since `math.sin` works with radians. Your first result is the correct one, with a little bit of numerical errors, which is to be expected when working with floating points variables. – Gilles-Philippe Paillé Nov 02 '19 at 17:00

0 Answers0