无法使用python绘制函数

2024-04-26 03:59:53 发布

您现在位置: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绘制函数,所以有人能给我一些帮助吗? 提前谢谢


Tags: 函数inforreturnifdefnpres
1条回答
网友
1楼 · 发布于 2024-04-26 03:59:53

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

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()

相关问题 更多 >