【问题标题】:Error: unsupported operand type(s) for -: 'list' and 'int'错误:不支持的操作数类型 -: 'list' 和 'int'
【发布时间】:2021-10-30 17:12:32
【问题描述】:

我正在尝试使用 Chebyshev 节点和拉格朗日多项式绘制图,如下所示,但我收到错误 x、y 和格式字符串不得为无。为什么会发生这种情况,我该如何解决它/绘制我想要的适当的东西?

编辑:我已更新我的代码以修复原始错误 x、y 和格式字符串不能为无,现在我有错误 unsupported operand type(s) for - : 'list' 和 'int'

import numpy as np

def lagrange(x, z, f):
    d = len(x)
    if len(x) != len(z):
        print("Error: the length of x and z is different")
    else:
        p = 0
        for i in range (d):
            L = 1
            for j in range (d):
                if j != i:
                    L *= (z-x[j])/(x[i] - x[j])
                p += f[i]*L
        return p
        

def f(x):
  return np.cos(x)

d = [0.1, 4, 0.2]
g = [-0.3, 0, 0.3]
lagrange(d, g, f(d)) 

【问题讨论】:

  • 问题是lagrange(d, g, f(d)) = None不能被绘制
  • 是否因为我没有正确定义我的函数而 =None?
  • 你的函数有两个问题:一个是输入因为len(d) = 10len(g) = 3 所以你到达print("Error: the length of x and z is different") 而且它没有返回任何东西,也许你想改变打印带return语句的语句,但还是需要解决输入问题
  • z 是一个列表,而所有其他都是数字,你不能在它们之间做减号和除法运算,但我不知道你想用那段代码做什么,所以我如果你不向我描述它应该做什么,我无法进一步帮助你
  • 我认为答案就是你要找的 :-)

标签: python numpy matplotlib


【解决方案1】:

你可以使用 np.array 解决这个问题:

import numpy as np

def lagrange(x, z, f):
    d = len(x)
    if len(x) != len(z):
        print("Error: the length of x and z is different")
    else:
        p = 0
        for i in range (d):
            L = 1
            for j in range (d):
                if j != i:
                    L *= (z-x[j])/(x[i] - x[j])
                p += f[i]*L
        return p
        

def f(x):
  return np.cos(x)


d = np.array([0.1, 4, 0.2])
g = np.array([-0.3, 0, 0.3])

lagrange(d, g, f(d)) 

这将返回array([-5.08984891, 1.04582888, 6.70431625])

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-08
    • 1970-01-01
    • 1970-01-01
    • 2012-12-12
    • 2018-10-19
    • 2016-05-31
    相关资源
    最近更新 更多