Try it on paper first. A hint, the key idea and the worked solution are here when you need them.
Ajay writes if math.sin(math.pi) == 0: and the program does not take the branch. He runs print(math.sin(math.pi)) and print(math.cos(math.pi / 2)). Both answers should be , but they are not. Each is a number like or times a power of ten. Give the power of ten in each, and say how Ajay should write his test.
Degrees to radians: multiply by . Python's trigonometric functions take radians: math.sin(math.radians(d)). The point at angle on the unit circle is . Floats carry a rounding error of about , so compare them with math.isclose, not ==.
Have you tried it?
Work it out on paper first. It is fine to get stuck or make a mistake: that is how we learn. When you are ready, go through the solution one step at a time, and check each step against your own.
Step 1. The sine. math.sin(math.pi) prints 1.2246467991473532e-16. The power of ten is .
Step 2. The cosine. math.cos(math.pi / 2) prints 6.123233995736766e-17. The power of ten is .
Step 3. Why. A float keeps about digits, so the stored is a tiny bit off, and the sine of it is a tiny number, not zero.
Step 4. The test. math.isclose(math.sin(math.pi), 0, abs_tol=1e-9) is True.
Answer: and , and a test with a tolerance.
Log in to join the discussion.
Loading…