【问题标题】:ufunc 'subtract' did not contain a loop with signature matching typesufunc“减法”不包含签名匹配类型的循环
【发布时间】:2016-06-02 19:44:08
【问题描述】:
import scipy as sy
import numpy as np
import re

from numpy import *

P = np.array(input('Please enter the P vector:\n'))
Q = np.array(input('\nPlease enter the Q vector:\n'))
R = np.array(input('\nPlease enter the R vector:\n'))


print('\n\nP: ',P)
print('Q: ',Q)
print('R: ',R)

#calculations for question 1
PQ=Q-P
magPQ= sy.sqrt(dot(PQ,PQ))
#calculations for question 2
PR= R-P
#calculations for question 3
QP = P-Q
QR = R-Q
magQP=sy.sqrt(dot(QP,QP))
magQR=sy.sqrt(dot(QR,QR))
angle=sy.arccos(dot(QP,QR)/(magQP*magQR))
angled=angle*180/sy.pi
#calculations for question 4
Area = sy.sqrt(dot(cross(PQ,QR),cross(PQ,QR)))
#calculations for question 5
magPR =sy.sqrt(dot(PR,PR))
perimeter = magPQ+magQR+magPR

######################OUTPUT#######################

print("Question 1. What is the distance between P and Q?")
print("Answer: ",round(q1,4))

print("\nQuestion 2. What is the distance vector from P to R?")
print('Answer: ',q2)

print("\nQuestion 3. What is the angle between QP and QR?")
print('Answer: ',angled)

print("\nQuestion 4. What is the area of the triangle PQR?")
print('Answer: ',Area)

print("\nQuestion 5. What is the perimeter of triangle PQR?")
print('Answer: ',perimeter)

上面是我的代码,当我尝试编译时,我得到了错误

Traceback (most recent call last):
File "Homework1-3.py", line 17, in <module>
PQ=Q-P
TypeError: ufunc 'subtract' did not contain a loop with signature matching types dtype('<U6') dtype('<U6') dtype('<U6')

能够输入我的数组非常重要,因为我希望这个程序能够解决问题。它似乎使用字符串而不是浮点数。我该如何解决这个问题?

【问题讨论】:

  • np.array(input('Please enter the P vector:\n')) - 您是否希望 解析 用户键入的字符串? np.array 不会那样做。
  • 不知何故我的 python 更新到 3.x,所以它似乎在 python 2.x 中有效
  • 如果您在 Python 2 上使用此代码,input 会在字符串上调用 eval(这是一个糟糕的想法,在 Python 3 中进行了正确的更改)。您还遇到了其他问题,例如使用 print 错误。
  • 我修复了 python 3 的打印,因为它是第一组抛出的错误消息。
  • 我删除了 np.从数组中,我仍然收到相同的错误消息

标签: python-3.x numpy scipy


【解决方案1】:

在我尝试过的交互式 ipython(3) 会话中:

In [373]: x=input('')
123,232,232

In [374]: x
Out[374]: '123,232,232'   # I got a single string from input

In [375]: np.array(x)
Out[375]: 
array('123,232,232',    # trying to make that an array - still string
      dtype='<U11')

In [377]: np.array(x.split(','))
Out[377]: 
array(['123', '232', '232'],     # better - 3 strings 
      dtype='<U3')

In [378]: np.array(x.split(','),dtype=float)
Out[378]: array([ 123.,  232.,  232.])    # good

我强烈建议您启动一个交互式 Python 会话,并测试代码的每一步。让它一块一块地工作。编写一开始就有错误的整个脚本并不是一种高效的编程方式或学习方式。

而当使用numpy数组时,看看shapedtype;不要假设数组是有意义或有用的。检查一下。

【讨论】:

  • 谢谢,虽然当我尝试最后一行代码时,我收到了 Traceback(最近一次调用最后):文件“Homework1-3.py”,第 8 行,在 P = np.array(P.split(','),dtype=float) AttributeError: 'numpy.ndarray' 对象没有属性 'split'
  • 您将split 应用于由input 生成的字符串,而不是应用于已通过np.array 的字符串。
猜你喜欢
  • 1970-01-01
  • 2023-04-03
  • 2021-11-23
  • 1970-01-01
  • 2016-08-06
  • 2018-07-25
  • 2019-03-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多