The problem of my formula in my simulation project (NaN)

I don’t understand how it could lead to NaN and how to fix it.

forceFunction = function(self,Particle_Object,DeltaTime)
			local ParticleTypeId = Particle_Object.ParticleTypeId
			local Position = Particle_Object.position

			local Position2 = self.position

			local Difference = (Position2-Position) --B - A
			local Distance = Difference.Magnitude
			
			local ForceFactor = rules[ParticleTypeId][math.floor(Distance)] or 0
			
			if Distance == 0 then
	        	self:apply_force(Vector2.new(math.random(-1,1),math.random(-1,1)))
		    	return
			end
			
			print(ForceFactor,DeltaTime,"a-1")
			print(Difference.Unit * ForceFactor * DeltaTime,"a")
			print(self.velocity,"b")
			
			self:apply_force(Difference.Unit * ForceFactor * DeltaTime)
		end;

NaN (meaning “Not a Number”) is some sort of number that is undefined or can’t be represented as a number. Common examples might include dividing 0 by 0, which is indeterminate, and taking the square root of a negative number, which results in an imaginary number but can’t be represented as a real number so it is undefined.

What could be a possible cause is taking the unit vector of the “Difference” vector (i.e: Difference.Unit). To get a unit vector, each component of the original vector is divided by the magnitude of that vector. In the case that Difference is a zero vector (i.e: all components x, y and z are 0), the magnitude is zero, so you end up dividing 0 by 0 which gives you NaN.

If you replace it with a non-zero vector then the problem will be resolved, but you haven’t explained what exactly you’re trying to do here for me to know the best solution

2 Likes