I'm coding on a specialized motion controller hardware which uses a subset of Visual Basic language as its programming language. I need to make some calculations on given points, like getting center coordinates of an arc that is passing through 3 distinct points; shifting lines, getting intersection coordinates of 2 lines etc...
I'm using cartesian coordinate system for calculations. It seems that the code will get bloated while handling divide by zero
cases.
So, what is the best coordinate system for such calculations? Or what is the best approach to keep such code small?
The code giving center point coordinates of an arc that is passing through 3 points is as follows:
' p1: (px1, py1) p2: (px2, py2) p3: (px3, py3)
' ----------------------------------------------
m_r=(py2-py1)/(px2-px1) ' slope of the line between p1 and p2
m_t=(py3-py2)/(px3-px2) ' slope of the line between p2 and p3
center_x=(m_r*m_t*(py3-py1)+m_r*(px2+px3)-m_t*(px1+px2))/(2*(m_r-m_t))
center_y=(-1/m_r)*(x_mrk-(px1+px2)/2)+(py1+py2)/2
As you can see, there are many cases that will cause a divide by zero
exception. Should I use if/else
structure or is there a better way?
When you calculate center point of an arc that is passing through 3 points, you definitely need to check if these points lies on the same line. But rewrite expression
if (py2-py1)/(px2-px1) = (py3-py2)/(px3-px2)
to avoid dividing
Det = (py2-py1) * (px3-px2) - (py3-py2) * (px2-px1)
if Det = 0 then ... `bad case
for else case (Det<>0) arc exists, and you can find center coordinates without zero-divide errors
center_x= ((py2-py1) * (py3-py2) * (py3-py1) +
(py2-py1) *(px2+px3) * (px3-px2) -
(py3-py2) * (px1+px2) * (px2-px1)) / (2 * Det)