【问题标题】:Squaring user input Values using POW使用 POW 对用户输入值进行平方
【发布时间】:2019-01-14 14:45:29
【问题描述】:

试图从用户输入中获取一系列值的均方根值,并且需要使用 POW 函数单独对所有值进行平方。

你好,

我正在尝试从用户输入中获取一系列值的 RMS,第一步是所有值都需要平方,但是在尝试编译要平方的数字时我不断收到错误(使用POW 函数)。我正在尝试在 tkinter GUI 中完成此操作。

def enter():
    entered_RMS=(entry_RMS.get())                    
    result_RMS = entered_RMS.split(' ')

    # Cast each element as an integer
    for i in range(len(result_RMS)):
        result_RMS[i] = int (result_RMS[i])

    #square each number
    SQR_RMS=pow(result_RMS,2)

    # Add all the elements together
    RMS_total = sum(SQR_RMS)

    #Find the mean by dividing by how many numbers entered
    mean= float (RMS_total/ len (SQR_RMS))

    #Find the mean by dividing by how many numbers entered
    mean= float (RMS_total/ len (SQR_RMS))


    label_RMS.configure(text=str(square)+ ' is the RMS')

错误是不断得到是

TypeError:** 或 pow() 不支持的操作数类型:'list' 和 'int'

据我了解,这是由于试图将 RMS_total 用作 int 并且它在 POW 函数中不起作用。

【问题讨论】:

  • result_RMS 是一个列表,您需要将pow 应用于其中的每个值。查找列表推导SQR_RMS = [pow(int(s), 2) for s in entered_RMS.split(' ')]
  • 感谢 jonrsharpe,非常有帮助!
  • pow 不是最好的方法。最好通过写 x*x 来平方 x。
  • 您可以轻松地将 lambda 写为 x*x 而不是 pow(x, 2)

标签: python math pow square-root


【解决方案1】:

你的意思是这样的:

import numpy as np
entered_RMS = '1 2 3 4 5'
print(np.sqrt(np.mean(np.array(list(map(float, entered_RMS.split(' '))))**2)))

【讨论】:

  • 这是一种更清洁的方法,没想到使用numpy,谢谢
  • 你应该标记回答你问题的答案
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-05-10
  • 1970-01-01
  • 1970-01-01
  • 2023-03-17
  • 2013-04-23
  • 2023-02-12
  • 2012-04-23
相关资源
最近更新 更多