无法使用 python 绘制函数

Can't draw function using python

我做了一个函数 RC(n),给定任何 n 都会根据规则改变 n 的数字。函数如下

def cfr(n):
    return len(str(n))-1


def n_cfr(k,n):
    J=str(k)
    if "." in J:
        J2=J.replace(".", "")
        return J2[n-1]
    else:
        return J[n]

def RC(n):
    if "." not in str(n): 
        return n+1
    sum=0
    val=0
    for a in range(1,cfr(n)+1):
        O=(int(n_cfr(n,a)))*10**(-a+1)
        if int(n_cfr(n,a))==9:
            val=0
        else:
            val=O+10**(-a+1)
        sum=sum+val
    return sum    

我想为 n 的非整数值绘制此函数。一位朋友给了我他在其他功能中使用的这段代码,但它似乎对我不起作用:

def draw(f,a,b,res):
import numpy as np
import matplotlib.pyplot as plt
    x=[a+(b-a)*i/res for i in range(0,res)]
    y=[f(elm) for elm in x]
    plt.plot(np.asarray(x), np.asarray(y))
    plt.show()

我不熟悉使用 python 绘制函数所以有人能帮我一些忙吗? 提前致谢

函数中的行应该是 x = list(range(a, b, res)) range 的前两个参数是 startstop。这是绘制的更好版本:

def draw(f, a, b, res):
    import numpy as np
    import matplotlib.pyplot as plt
    x = list(range(a, b, res))
    plt.plot(x, map(f, x))
    plt.show()