From: Phillip Gawlowski Date: 2008-03-31T18:59:08+09:00 Subject: Re: Is it me or Math::sqrt? -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Robert Klemme wrote: | 2008/3/31, Phillip Gawlowski : |> # Calculates the relative distance_to an arbitrary |> # Note: The algorithm is not yet optimized for speed. |> # Hopefully, it is accurate, though. |> def distance_to(actor) |> # Stub, will use vector math or so to approximate the true distance |> distance = (self.x - actor.x)^2 + (self.y - actor.y)^2 + (self.z - |> actor.z)^2 |> Math::sqrt(distance.abs) |> end |> |> actor1 = Gondor::AI::Actor.new(:x => 0,:y => 0,:z => 0) |> actor2 = Gondor::AI::Actor.new(:x => 16, :y => 16, :z => 16) |> actor1.distance(actor2) |> produces: 3.74165738677394 |> |> actor1 = Gondor::AI::Actor.new(:x => 1,:y => 1,:z => 1) |> actor2 = Gondor::AI::Actor.new(:x => 15, :y => 15, :z => 15) |> produces: 4.0 |> |> Why is that? From my understanding, these results should be identical |> (The algebraic sign is eliminated by exponent 2, everything else is |> addition). |> |> Another thing that has me stumped is, that Math::sqrt requires the |> absolute, but the result should be positive (addition of positive |> algebraic signs). |> |> Do I need to brush up my math more than I thought? | | - without words - | | irb(main):002:0> (0-16)^2 | => -14 | irb(main):003:0> (0-16) ** 2 | => 256 | | :-) | | Kind regards | | robert | I've replaced ^2 with ** 2, but that doesn't seem to change the magnitude of the error (Though, the results "feels" more correct now, so thanks for that). The results are still different, as you can see: 24.2487113059643 for actor1's x,y,z = 1, and actor2's x,y,z = 15 27.712812921102 for actor1's x,y,z = 0, and actor2's x,y,z = 16 However, since the coordinates are subtracted on their respective axises, I guess that my assumption on the "error" is incorrect, and that I do get the correct value. However, intuitively, the distance between these two points should be the same. Hmmmm.. - -- Phillip Gawlowski -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.8 (MingW32) Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org iEYEARECAAYFAkfwtewACgkQbtAgaoJTgL+8oACfelpzNMjMyhvl6x4tfJi6M/2f /m4AnA0T46orBD6hnv7g6YCsb60PZdzC =ANtA -----END PGP SIGNATURE-----