如何解决Manim中(1+1/x)**x函数的除零报错并保留全范围坐标轴
解决Manim中(1+1/x)**x函数除零报错并保留-10到10坐标轴范围的问题
问题重现
你在Manim里绘制 (f(x) = (1+\frac{1}{x})^x) 时,因x=0处的除零操作触发报错,且需要保留x、y轴-10到10的范围。原代码和报错如下:
原代码
self.axes = Axes( x_range=(-10, 10, 3), y_range=(-10, 10, 3) ) self.f = lambda x: (1+1/x)**x curve = self.axes.plot(self.f, color= RED) self.play(Create(self.axes), Create(curve)) self.interactive_embed()
报错信息
array must not contain infs or NaNs
RuntimeWarning: invalid value encountered in double_scalars
self.f = lambda x: (1+1/x)**x
你试过调整坐标轴步长为3来跳过x=0,但没用;只有把x范围改成(1,10)才能正常运行,但不符合需求。
解决方案
方案1:给函数加无效值过滤
原函数的定义域是x≠0且x不是负整数(负整数时底数为0或负数,实数范围内没意义)。用numpy的where把这些无效x值转换成NaN,Manim遇到NaN会自动跳过对应点,不会报错:
import numpy as np self.axes = Axes( x_range=(-10, 10, 3), y_range=(-10, 10, 3) ) self.f = lambda x: np.where( # 过滤x=0和负整数 (x == 0) | ((x < 0) & (x == np.floor(x))), np.nan, (1 + 1/x)**x ) curve = self.axes.plot(self.f, color=RED) self.play(Create(self.axes), Create(curve)) self.interactive_embed()
方案2:分左右区间绘制曲线
直接把曲线分成x>0和x<0两部分绘制,完全避开x=0附近的区域,还能通过num_samples参数让曲线更平滑:
self.axes = Axes( x_range=(-10, 10, 3), y_range=(-10, 10, 3) ) def f(x): return (1 + 1/x)**x # 绘制x>0的部分,从0.01开始避开除零 curve_right = self.axes.plot(f, x_range=(0.01, 10), color=RED, num_samples=1000) # 绘制x<0的部分,到-0.01结束,同时自动跳过负整数的无意义点 curve_left = self.axes.plot(f, x_range=(-10, -0.01), color=RED, num_samples=1000) self.play(Create(self.axes), Create(curve_right), Create(curve_left)) self.interactive_embed()
方案3:指定plot的有效采样范围
Manim的plot方法默认会在整个坐标轴x范围内采样,哪怕你设了步长3,采样点还是可能碰到x=0。直接给plot传x_range参数,限定只在有效区域采样:
self.axes = Axes( x_range=(-10, 10, 3), y_range=(-10, 10, 3) ) self.f = lambda x: (1+1/x)**x # 左半部分从-10到-0.01,右半部分从0.01到10,都避开x=0 curve_left = self.axes.plot(self.f, x_range=(-10, -0.01), color=RED) curve_right = self.axes.plot(self.f, x_range=(0.01, 10), color=RED) self.play(Create(self.axes), Create(curve_left), Create(curve_right)) self.interactive_embed()
补充说明
- 方案1改动最小,适合快速修复;方案2、3更灵活,能精准控制绘制范围,加
num_samples可以让曲线更顺滑。 - 注意原函数在负整数x处没有实数解,所以x<0的曲线会有间断,这是函数本身的特性,不是代码问题。
内容的提问来源于stack exchange,提问作者Мазуз Азуавов
相关产品推荐
相关产品推荐

