3b1b / manim

Animation engine for explanatory math videos
MIT License
62.64k stars 5.81k forks source link

fix: `there_and_back_with_pause` #2134

Closed jkjkil4 closed 3 weeks ago

jkjkil4 commented 4 months ago

Motivation

I find a bug when using there_and_back_with_pause.

Proposed changes

fix the behaviour of there_and_back_with_pause when setting pause_ratio with other values.

Test

Code:

# In[]
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.axes import Axes

def smooth(t: float) -> float:
    s = 1 - t
    return (t**3) * (10 * s * s + 5 * s * t + t * t)

def there_and_back_with_pause(t: float, pause_ratio: float = 1.0 / 3) -> float:
    a = 1. / pause_ratio
    if t < 0.5 - pause_ratio / 2:
        return smooth(a * t)
    elif t < 0.5 + pause_ratio / 2:
        return 1
    else:
        return smooth(a - a * t)

def there_and_back_with_pause_corrected(t: float, pause_ratio: float = 1. / 3) -> float:
    a = 2. / (1. - pause_ratio)
    if t < 0.5 - pause_ratio / 2:
        return smooth(a * t)
    elif t < 0.5 + pause_ratio / 2:
        return 1
    else:
        return smooth(a - a * t)

def plot(axes: Axes, func, pause_ratio: float, aspect_eq=True) -> None:
    axes.set_title(f'...{func.__name__[14:]}(t, pause_ratio={pause_ratio:.3f})',
                   fontsize=9)
    if aspect_eq:
        axes.set_aspect('equal')
    else:
        axes.set_aspect(1 / 5500)
    x = np.linspace(0, 1, 100)
    y = [func(v, pause_ratio=pause_ratio) for v in x]
    axes.scatter(x, y, s=3)

fig = plt.figure(figsize=(6, 10))

plot(fig.add_subplot(4, 2, 1), there_and_back_with_pause, 0.1, False)
plot(fig.add_subplot(4, 2, 3), there_and_back_with_pause, 1 / 3)
plot(fig.add_subplot(4, 2, 5), there_and_back_with_pause, 0.5)
plot(fig.add_subplot(4, 2, 7), there_and_back_with_pause, 0.8)

plot(fig.add_subplot(4, 2, 2), there_and_back_with_pause_corrected, 0.1)
plot(fig.add_subplot(4, 2, 4), there_and_back_with_pause_corrected, 1 / 3)
plot(fig.add_subplot(4, 2, 6), there_and_back_with_pause_corrected, 0.5)
plot(fig.add_subplot(4, 2, 8), there_and_back_with_pause_corrected, 0.8)

fig.tight_layout()
fig.show()

# %%

Result:

the picture below shows the bug of there_and_back_with_pause (left), and the corrected result (right)

image