Python cos (90) and cos (270) are not 0

What's happening?

Checking the sin and cos functions to find out why I get such excellent positioning in the wrong places when outputting coordinates to an SVG file. So I did this test code, which I can predict that the answer should figure out why. Strange nothing that affects the calculation, he adds this behavior, but just the position where I am going to stay. If the position is 0 and after calculation it becomes 0, but if the position is 1 and becomes 1 after calculation, it will work.

First test:

import math cX = 2 cY = 2 r = 2 rcX = cX + (r * math.cos(math.radians(0))) rcY = cY + (r * math.sin(math.radians(0))) print rcX #4 print rcY #2 r = 1 rlX = rcX + (r * math.cos(math.radians(90))) rlY = rcY + (r * math.sin(math.radians(90))) print rlX #4 print rlY #3 r = 4 flX = rlX + (r * math.cos(math.radians(180))) flY = rlY + (r * math.sin(math.radians(180))) print flX #0 print flY #3 r = 2 print r * math.cos(math.radians(270)) print flX + (r * math.cos(math.radians(270))) #-3.67394039744e-16 should be 0 print flY + (r * math.sin(math.radians(270))) #1 

Now I change cX to 3, and it works, even if it does not affect the calculation:

 r * math.cos(math.radians(270)) 

The result of this calculation is added to the x coordinate

 import math cX = 3 cY = 2 r = 2 rcX = cX + (r * math.cos(math.radians(0))) rcY = cY + (r * math.sin(math.radians(0))) print rcX #5 print rcY #2 r = 1 rlX = rcX + (r * math.cos(math.radians(90))) rlY = rcY + (r * math.sin(math.radians(90))) print rlX #5 print rlY #3 r = 4 flX = rlX + (r * math.cos(math.radians(180))) flY = rlY + (r * math.sin(math.radians(180))) print flX #1 print flY #3 r = 2 print r * math.cos(math.radians(270)) print flX + (r * math.cos(math.radians(270))) #1 print flY + (r * math.sin(math.radians(270))) #1 
+4
source share
2 answers

Indeed, this is a very low number, terribly close to zero. Here's a great article to help you understand common problems and traps of floats: " What Every Computer Scientist Should Know About Floating-Point Arithmetic "

+7
source

You are dealing with rounding errors that are (mostly) inevitable when working with floating point maths (see a document already linked by others to understand exactly what is happening).

In many cases, you can reduce their influence (by performing operations in an "intelligent" order or reformulating your expressions more "floating point"), but the simplest thing in your situation is simply the results, for example 6 decimal places and be happy. Of course, you do not need more accuracy in positioning, and you get the results expected for the "canonical" angles.

+5
source

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


All Articles