简体   繁体   English

Python:在复杂方程中使用 math.sqrt 函数

[英]Python: using the math.sqrt function in a complex equation

I am trying to write code to solve this python exercise: I must use the 'math' library, sqrt and possibly pow functions.我正在尝试编写代码来解决这个 python 练习:我必须使用“数学”库、sqrt 和可能的 pow 函数。

"The distance between two points x and y is the square root of the sum of squared differences along each dimension of x and y. “两点 x 和 y 之间的距离是沿 x 和 y 的每个维度的平方差之和的平方根。

"Create a function that takes two vectors and outputs the distance between them. “创建一个函数,它接受两个向量并输出它们之间的距离。

x = (0,0) y = (1,1)" x = (0,0) y = (1,1)”

So far I've tried this - which certainly hasn't worked.到目前为止,我已经尝试过了——当然没有用。

x = (0,0)
y = (1,1)
(c1, c2) = x
(c3, c4) = y
math.sqrt(sum((c1,**2)(c2,**2)(c3,**2)(c4,**2)))
 File "<ipython-input-14-ac0f3dc1fdeb>", line 1 math.sqrt(sum((c1,**2)(c2,**2)(c3,**2)(c4,**2))) ^ SyntaxError: invalid syntax文件“<ipython-input-14-ac0f3dc1fdeb>”,第 1 行 math.sqrt(sum((c1,**2)(c2,**2)(c3,**2)(c4,**2)) ) ^ SyntaxError: 语法无效
if c1 < c3:
    difference1 = c3-c1
    print(difference1)

1 1个

... not even sure if that's the kind of calculation I should be working with. ...甚至不确定这是否是我应该使用的那种计算。

def distance(x, y):

ummm... I expect the function starts by unpacking the tuples, But not sure how to write the rest of it.嗯...我希望函数从解包元组开始,但不确定如何编写其余部分。 or cleanly.或干净利落。

I'm a beginner programmer & not a mathematician so I may be wrong in more than one sense... This exercise is from this HarvardX course: 'Using Python for Research' .我是一名初级程序员,而不是数学家,所以我可能在不止一个意义上是错的……这个练习来自这个 HarvardX 课程: “使用 Python 进行研究”

It's OK to search for solutions via StackOverflow for learning on this course... not cheating to ask for pointers.可以通过 StackOverflow 搜索解决方案来学习本课程……不要作弊以寻求指点。

Many thanks for any ideas.非常感谢任何想法。 I will keep searching around.我会继续四处寻找。

import math
def distance (x,y):
    value= math.sqrt ((x[0]-y[0])**2 + (x[1] - y[1])**2)
    print (value)
distance((0,0), (1,1))

Thanks so much for those ideas.非常感谢这些想法。 I figured it out.我想到了。 So happy.很高兴。

for (a,b) in x,y:
    dis = math.sqrt((y[0] - x[0])**2 + (y[1] - x[1])**2)
    print(dis)
import math
def distance(x1,x2,y1,y2):

    x=(x1,x2)
    y=(y1,y2)
    dis = math.sqrt((x[1]-x[0])**2 + (y[1] - y[0])**2)
    return dis

print(dis(0,0,1,1))

this works very well to answer your quest这非常适合回答您的问题

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM