我想看看 Python 计算平方根的方式,所以我试图找到 的定义math.sqrt()
,但在任何地方都找不到。我查看过_math.c
、mathmodule.c
和其他地方。
我知道 python 使用 C 的数学函数,但这些是 Python 发行版中的某个地方,还是它们链接到其他地方的代码?我正在使用 Mac OS X。
算法在math.sqrt()
哪里?
It depends on the implementation. CPython is using math functions from the standard C library. Jython is most likely using Java's math methods. And so on.
In fact, Python has nothing to do with the actual implementation of math functions. Those are more related to IEEE 754 which is used almost exclusively to represent floating point numbers in computers nowadays.
Anyway, speaking in terms of CPython, its math
module is just a thin wrapper over C functions (prooflink, at the bottom of the page). The C functions are implemented as part of the standard C library. It is usually included in OS distributions and it is most likely distributed in binary form, without sources. Note also that many microprocessors have specialised instructions for some of these operations, and your compiler may well make use of those rather than jumping to the implementation in the C library.
I can't tell you the exact algorithm which is used in the standard C library on your system. Some of the possible algorithms are explained here.
In the specific case of OS X, the math functions live in libSystem.dylib
, which unfortunately is not Open Source (there is only stub code available on Apple's Open Source site). You can however disassemble it if you are interested - on current systems, try e.g.
otool -tvV /usr/lib/system/libsystem_m.dylib
有些模块是用 C 而不是 python 编写的,因此您将无法找到 .py 文件。对于这些列表,您可以使用:
import sys
print sys.builtin_module_names
由于它是用 C 编写的,因此您必须在源代码中找到它。如果您已经拥有源代码,则它位于模块目录中。
对代码进行简单的 grep 操作会有所帮助:
http://svn.python.org/view/python/trunk/Modules/cmathmodule.c?revision=76978&view=markup
我不确定在哪里可以找到 Python 使用的确切算法,但我希望这对您有所帮助。在 Python 中计算平方根的最简单方法是使用 **(幂)运算符。我不知道您对索引做了多少工作,但平方根与将某些东西的幂次方相同。因此,如果这是真的,您可以使用:
print x**0.5
这将打印您放在 x 位置的任何数字的平方根。当然,如果您使用的是 Python 3,那么您需要将其编写为:
print(x**0.5)
这将是制作算法来计算数字的平方根的最简单方法。这可以在一个函数中实现,例如:
sqrt(x):
return x**0.5
对于其他根,例如三次根等,您可以使用如下函数:
root(x, root):
return x**root
当您将根号传递给函数时,使用十进制形式的索引号,例如:
2:0.5
3:0.33333333(重复)
4:0.25
5:0.2
我希望你能看到模式。我也希望这对你有所帮助!:)