在Python中,“2*2”和“2**2”有什么区别?

55

以下两个语句有什么不同之处?

语句1:

var=2**2*3

语句 2:

var2=2*2*3

我看不出有什么区别。 这引发了以下问题。

如果我们可以使用语句2,为什么要使用语句1?


54
做数字测试时,请遵循以下两个规则:只使用质数(你做得对),并且不要两次使用2。 - Luc M
10个回答

127

尝试:

2**3*2

2*3*2
< p > ** 是“乘方”的运算符。在您的特定操作中,2的平方与2乘以2产生的结果相同。


9
http://docs.python.org/reference/expressions.html#the-power-operator 和 http://docs.python.org/reference/expressions.html#binary-arithmetic-operations 很重要,建议 @Masi 阅读。将提高你的编程能力。 - S.Lott
刚刚尝试了使用mmap()**。本以为它们的语义类似于//,但我错得离谱。我从未见过计算机对我如此生气。 - Qix - MONICA WAS MISTREATED
你知道哪个更有效率吗?10*2 还是 1010? - Boyan Kushlev

34

双星号 (**) 代表乘方。因此,“2乘以2”和“2的二次幂”是相同的,更换数字后你会看到不同。


6
实际上,在任何使用脱字符 (^) 表示按位异或操作的语言中,双星号都很常见。我认为除了表示指数运算之外,我没有看到双星号有其他含义。 - Mark Rushakoff
2
它们在很久很久以前被用于FORTRAN。 - David Thornley
3
双星号在Fortran中被引入为一种幂运算符,因为该语言没有位运算符号。 - Martin Beckett
3
有趣的事实:Google同时使用^和**。 - OscarRyz
4
@Martin:Fortran的诞生早于ASCII字符集,因此它不能依赖于^字符的可用性。 - dan04

14
  2**2 means 2 squared (2^2)
  2*2 mean 2 times 2 (2x2)
在这种情况下,它们恰好有相同的值,但是...
  3**3*4 != 3*3*4

9

对于视觉学习者..........................

在此输入图片描述


4

To specifically answer your question Why is the code1 used if we can use code2? I might suggest that the programmer was thinking in a mathematically broader sense. Specifically, perhaps the broader equation is a power equation, and the fact that both first numbers are "2" is more coincidence than mathematical reality. I'd want to make sure that the broader context of the code supports it being

var = x * x * y
in all cases, rather than in this specific case alone. This could get you in big trouble if x is anything but 2.


2

2**2 = 2的平方

2*2 = 2乘以2


2

在Python中,** 运算符实际上是“幂运算”,即 2**3 = 8


1

幂运算比乘法优先级更高,因此:

2**2*3 = (2^2)*3
2*2*3 = 2*2*3

1

顶部的一个符号是“幂”运算符,在这种情况下它相当于2 * 2等于2的2次方。如果你在中间位置放入一个3,你会发现有所不同。


1
一个双星号表示乘方。一个单星号表示乘。22相当于2x2,这就是为什么两个答案都是4的原因。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接