Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Other Lerp floating point precision improvement

Discussion in 'Scripting' started by LegacySystem, Jul 18, 2023.

  1. LegacySystem

    LegacySystem

    Joined:
    Jan 28, 2021
    Posts:
    52
    DevDunk likes this.
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    36,561
    Just so you know, you actually did not reimplement Mathf.Lerp().

    You actually reimplemented
    Mathf.LerpUnclamped()


    That's a WAAAAAAY different function!!

    For comparison:

    https://docs.unity3d.com/ScriptReference/Mathf.Lerp.html

    https://docs.unity3d.com/ScriptReference/Mathf.LerpUnclamped.html

    You may get back to .Lerp() by pre-clamping your
    t
    term to [0-1]
     
  3. LegacySystem

    LegacySystem

    Joined:
    Jan 28, 2021
    Posts:
    52
    Thank you for pointing it out. I was referring to output implementation. Clamp is done to "t". If I am not mistaken, clampped "t" is still accountable for a floating-point rounding error. But you are right, it was not clear on initial post.

    inside Mathf.cs:

    upload_2023-7-18_16-47-38.png
     
  4. Bunny83

    Bunny83

    Joined:
    Oct 18, 2010
    Posts:
    3,494
    It should be mentioned that both implementations have advantages and disadvantages. While the classical alpha blend method (
    t
    and
    1-t
    ) provide the best stability at the extremes, the direction vector approach is better in actually following the line / vector. Doing a normal linear "blend" between two positions could get some jerky in between values that do not necessarily follow a nice straight line.

    So I would not recommend to blindly replacing one with the other unless you have a specific reason and you know about all the implications. Which one is better highly depends on the usecase. Unity's lerp could be "improved" by implementing an early exit in case t is greater or equal to 1.

    upload_2023-7-18_18-38-12.png
    As you can see in this image, this is what a linear blend actually does. The green line is the one in question adn it's a scaled linear combination between A and B. So due to floating point rounding you can imagine that the point on the red line may be slightly off.since it's a combination of those two scaled segments.

    The vector approach always has the same stable start point and is adding a scaled version of the red line to the start point. So if something jitters, it jitters along the desired line.
     
    Last edited: Jul 18, 2023
    Kurt-Dekker likes this.