使用numpy piecewise和matplotlib绘制无理函数

时间:2016-03-01 18:36:27

标签: python-3.x numpy matplotlib

我正在尝试使用matplotlib在Numpy中使用分段绘制一个Irrational函数,但我有一个错误,我的代码:

import numpy as np
import matplotlib.pyplot as plt


p = np.poly1d([-4., 32., -64., 0., 1.])
roots = p.r
print(roots)
print(p(-.5), p(0.), p(4.), p(5.))
x = np.linspace(-1., 5.)
radical = 1. - (8. * x - 2. * x ** 2.) ** 2.
piece = (4. * x - 8.) / np.sqrt(radical)
func = np.piecewise(x, [(roots[3] < x) & (x < roots[2]), (roots[1] < x) & (x < roots[0])], [piece, piece])
plt.grid('on')
plt.plot(x, func, 'b-')
plt.legend([r'$g_3(x)=\frac{4x-8}{\sqrt{1-\left(8x-2x^2\right)^2}}$'], loc='best')
plt.title(r'$Función\;Punto\;Fijo$')
plt.savefig('ecuacioncoseno2.png', bbox_inches='tight')
plt.show()

我的输出就是这个:

   [ 4.12132034  3.87082869  0.12917131 -0.12132034]
    -19.25 1.0 1.0 -99.0
    C:\Anaconda3\lib\site-packages\ipykernel\__main__.py:7: RuntimeWarning: invalid value encountered in sqrt
    ---------------------------------------------------------------------------
    ValueError Traceback (most recent call last)
    <ipython-input-20-8194dfb84e77> in <module>()
          6 radical = 1. - (8. * x - 2. * x ** 2.) ** 2.
          7 piece = (4. * x - 8.) / np.sqrt(radical)
    ----> 8 func = np.piecewise(x, [(roots[3] < x) & (x < roots[2]), (roots[1] < x) & (x < roots[0])], [piece, piece])
          9 plt.grid('on')
         10 plt.plot(x, func, 'b-')

    C:\Anaconda3\lib\site-packages\numpy\lib\function_base.py in piecewise(x, condlist, funclist, *args, **kw)
        779         item = funclist[k]
        780         if not isinstance(item, collections.Callable):
    --> 781             y[condlist[k]] = item
        782         else:
        783             vals = x[condlist[k]]

    ValueError: NumPy boolean array indexing assignment cannot assign 50 input values to the 2 output values where the mask is true

我不知道是什么问题。 感谢

1 个答案:

答案 0 :(得分:0)

好吧,我的错误是在一个numpy分段函数中你必须将特定的函数块定义为lambda函数。这是我的代码解决方案:

import numpy as np
import matplotlib.pyplot as plt


p = np.poly1d([-4., 32., -64., 0., 1.])
roots = p.r
print(roots)
x = np.arange(roots[3], roots[2], .001)
x1 = np.arange(roots[1], roots[0], .001)
x = np.append(x, x1)
func = np.piecewise(x, [(roots[3] < x) & (x < roots[2]), (roots[1] < x) & (x < roots[0])], 
                    [lambda x: (4. * x - 8.) / np.sqrt(1. - (8. * x - 2. * x ** 2.) ** 2.), 
                     lambda x: (4. * x - 8.) / np.sqrt(1. - (8. * x - 2. * x ** 2.) ** 2.)])
pos = np.where(np.abs(np.diff(func)) >= 10.)[0] + 1
x = np.insert(x, pos, np.nan)
func = np.insert(func, pos, np.nan)
plt.ylim(-50., 50.)
plt.grid('on')
plt.plot(x, func, 'b-')
for i in roots:
    plt.vlines(i, -100, 100, colors='red', linestyles='dashed')
plt.legend([r'$g_3(x)=\frac{4x-8}{\sqrt{1-\left(8x-2x^2\right)^2}}$', r'$x=-0.12132034$', 
            r'$x=0.12917131$', r'$x=3.87082869$', r'$x=4.12132034$'], loc='best')
plt.title(r'$Función\;Punto\;Fijo\;3$')
plt.savefig('ecuacioncoseno2.png', bbox_inches='tight')
plt.show()

这是一张图片 enter image description here