简体   繁体   中英

Same code returns different results

Given the following algorithm:

public static void Casteljau(Vector3 p1, Vector3 p2, Vector3 p3 , Vector3 p4, ArrayList L)
{
    float stepping = (float)(0.02);

    for (float x = 0.0f; x <= 1.0f; x += stepping)
    {
        Vector3 ap1 = Vector3.Lerp(p1, p2, x);
        Vector3 ap2 = Vector3.Lerp(p2, p3, x);
        Vector3 ap3 = Vector3.Lerp(p3, p4, x);

        Vector3  bp1 = Vector3.Lerp(ap1, ap2, x);
        Vector3  bp2 = Vector3.Lerp(ap2, ap3, x);

        Vector3  p = Vector3.Lerp(bp1, bp2, x);

        L.Add(p);
    }
}

Which gets four points and return a list of points representing the curve between them, and given the same four points passed to this function, I get different results in two different ends\\clients. One of the calculated points had a little deviation of 0.1f value between the runs (its very small difference, but critical to my use).

This algorithm is used in a multiplayer game (using Unity3D) and both ends running this algorithm with the exactly same four points.

Every value of a Vector is float, language is C# , both ends runs on the same PC (one client is running using Unity editor, another one is an executabe built from Unity), OS in Windows .

Lerp function- http://docs.unity3d.com/ScriptReference/Vector3.Lerp.html

If 0.1 accuracy is important to your eyes working with doubles might be a better idea since every calcul made with floats adds up some imprecisions. In your case you are in a for loop working with floats so a few imprecisions can cause the big difference.

There is a good stackOverflow answer about this: Floating point inaccuracy examples

A suggestion would be to wrap these vector3 into a double version of vector3. As for the the difference between the exe and the editor it is porbably because the Exe and the editor are not built for the same target. and the ressources available for both of them are not quiet the same. Now if on the same PC you manage to find a difference you probably wont be able to obtain clean result from multiple PC that are not on the same architecture.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM