【问题标题】:How can i solve Type Error in using Numpy我如何解决使用 Numpy 时的类型错误
【发布时间】:2021-03-18 04:45:35
【问题描述】:

为什么我出错了?你能帮忙修改一下我的代码吗?

-TypeError: 类型的对象不能安全地解释为整数。

-TypeError: 'float' 对象不能被解释为整数

import numpy as np
import matplotlib.pyplot as plt

def f(x):
    return x**3-2*x
def inputNumber(message):
     while True:
        try:
           userInput =float(input(message))  
        except ValueError:
           print("Enter valid")
           continue
        else:
           return userInput 
           break
 

interval1=float(inputNumber("Please write lower bound: "))
interval=float(inputNumber("Please write upper bound: "))
stepsize=float(inputNumber("Enter a step size: "))

x = np.linspace(float(interval1),float(interval),float(stepsize))
y = f(x)

【问题讨论】:

  • 你为什么使用float(stepsize)?文档说该步骤应该是一个整数!

标签: python numpy error-handling


【解决方案1】:

linspace 的前三个参数是开始、结束和要生成的样本数 - 而不是步长。试试np.arange(interval1, interval, stepsize)

或者,您可以使用:num = round((interval-interval1) / stepsize) 计算样本数,然后将其插入 linspace:np.linspace(interval1, interval, num),但我不建议使用它来代替 arange

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-20
    • 1970-01-01
    • 2016-01-25
    • 1970-01-01
    相关资源
    最近更新 更多