Monday, August 14, 2017

c# - margin of error trying to check if a point lays on line


Working with floating point values it is as easy as breathing to run on approximation errors by comparing quantities which should be the same. I want to know if there is a way built in some MSDN (or even external) library for c# to ignore the problem.


An example could be: more than comparing 2 float values like this


if(myVector3.X == anotherVector3.X)

I would appreciate something like this



if(myVector3.X.isInTheNeighbourhood(anotherVector3.X))

This is not well-written, I know. That is just to simplify the explaination. What I am exactly doing is checking if a point (Vector3) lays on line segment. So basically the calculations I make are nothing more than


(x - x1)/(x2 - x1) = (y - y1)/(y2 - y1) = (z - z1)/(z2 - z1)

But these values won't be always the same, so I need to write down some code which includes a sort of tolerance a sort of Neighbourhood mathematical concept to accept values close enought to the line.


Hope that I made myself clear. Has anyone a solution for this?



Answer



In order to take into consideration the floating point error you need to do the following:


\#define ERR 1e-9

if( fabs (myVector3.X - anotherVector3.X) <= ERR )

Keep in mind that this kind of approximation changes the geometrical properties of the shape, for instance this can generate fat planes/lines. a case where a line or a plane no more has zero width. But as far as you don't need exact calculations such as those needed in geometry analysis it's fine for a game. Here is a link where it explains the problem in using floating points in geometry.


enter image description here


There are other methods to solve the error problem and get exact results, but they are far too complex or far too slow. So non of them from my experience with geometry fit the requirements of the real time video games.


No comments:

Post a Comment

Simple past, Present perfect Past perfect

Can you tell me which form of the following sentences is the correct one please? Imagine two friends discussing the gym... I was in a good s...