I was checking my understanding of what Magnitude is, and so far everything was going alright, but then I got this NaN error.
Furthermore, the equation for magnitude on a 3d Vector looks like this:
V = Vector
Vx, Vy, Vz = Vector components
||V|| = sqrt(Vx^2, Vy^2, Vz^2)
You can utilize this in Roblox with Vector3().Magnitude.
However, after applying negative numbers into a Vector3, I get this NaN error. Heres the code:
--3D Magnitude Equation; ||V|| = ?(x^2 + y^2 + z^2) local newVector = Vector3.new(10, 10, 10) print(newVector.Magnitude) local magnitude3d = math.abs((math.sqrt((-10^2) + (-10^2) + (-10^2)))) print(magnitude3d)
17.320508956909
nan
However, if I change the components in magnitude3d
to all be positive, the numbers come out as expected.
local newVector = Vector3.new(10, 10, 10) print(newVector.Magnitude) local magnitude3d = math.abs((math.sqrt((10^2) + (10^2) + (10^2)))) print(magnitude3d)
17.320508956909
17.320508075689
This makes absolutely 0 sense to me at the moment. Math.abs() returns the absolute value of the number (it would always be positive). Also, if you square a number, the answer will always be positive, even if it's a negative number. I'm not quite understanding whats going on.
Another thing to be noted:
local newVector = Vector3.new(-10, -10, -10) print(newVector.Magnitude)
17.320508075689
Even if the components of a Vector3 are negative, it works here. So whats the deal? Is it because im taking the square root, or because i'm adding the squares of numbers together?
No idea. Thanks for anyone who knows enough about Lua to know why this error happens. And thanks if you even read this far, most people would be like, "Ew math" lol.
Ok, had a buddy of mine help me solve this.
So although -10 * -10 = 100
, lua interprets it as -(10 * 10)
when you write -10^2
So, this means that the initial equation will be -300 if we printed it without the square root or absolute value being taken.
So, I can easily fix this by simply switching the math operations around, or rewriting it a bit. This doenst fit with the initial equation, since it calls for taking the absolute value of the solution, but thats alright.
local magnitude3d = math.sqrt(math.abs((-10^2) + (-10^2) + (-10^2))) print(magnitude3d)
17.320508075689
Shoutout to homeboy Guges & Elixcore who helped me realize that. I had no idea thats how lua was interpreting those numbers.