It is not unusual for physics simulation programs to use unit vectors.
Physics simulation programs tend to have large sets of data and can benefit significantly through vectorization.
In these types of programs it may be rare, but not impossible, to have a separation of particles of 0.0, thus making the statement(s) that produces the unit vector containing a divide by 0.0. In the cases where separation is 0.0, you do not want to abort the program, instead you usually want to do something else, such as produce a unit vector of 0.0, or alternately a random unit vector.
A defensive measure is to insert a test for 0.0, and when found, perform the alternate substitution.
The problem with this is the test quashes vectorization.
ab(index,1:3) = b(index,1:3) - a(index,1:3) separation(index) = sqrt(ab(index,1)**2 + ab(index,2)**2 + ab(index,3)**2) if(separation(index) .eq. 0.0) then uv(index,1:3) = 0.0 else uv(index,1:3) = ab(index,1:3) / separation(index) endif
What I would like to suggest is for the compiler optimization gurus to recognize the code sequence is a divide by 0.0 defensive code sequence with a known substitution, in this case 0.0, but it could be someOtherValue(1:3).
Then, when determined safe, have the loop disable divide by zero fault an substitute
uv(index,1:3) = ab(index,1:3) / separation(index) if(uv(index,1) .eq. Infinity) uv(index,1) = Substitutio(1) if(uv(index,2) .eq. Infinity) uv(index,2) = Substitutio(2) if(uv(index,3) .eq. Infinity) uv(index,3) = Substitutio(3)
While the above looks ugly in source code, it can use masked moves (amongst temporary vector registers)
The above optimization removes code branching and thus improves probability of vectorizing loops containing defensive code for divide by 0.
Jim Dempsey