ferm中的数学域错误

2024-09-29 21:46:36 发布

您现在位置:Python中文网/ 问答频道 /正文

from math import sqrt

def fermatBook (n):
    x=int(sqrt(n))
    c=x**2-n
    while (sqrt(c)!=int(sqrt(c))):
        x=x+1
    y=sqrt(c)
    a=x+y
    b=x-y
    if a==1 or b==1:
        print "The number is prime"
    return a, b

错误:

Traceback (most recent call last):
  File "<pyshell#0>", line 1, in <module>
    fermatBook (23867)
  File "C:/Python27/fermatLivro.py", line 6, in fermatBook
    while (sqrt(c)!=int(sqrt(c))):
ValueError: math domain error

我不知道程序出了什么问题。。。有人能帮我吗?你知道吗


Tags: ortheinfromimportifdefline
1条回答
网友
1楼 · 发布于 2024-09-29 21:46:36

很可能变量c为负:

示例

如果您致电:

n = 2 
fermatBook(n)

它将为以下变量分配以下值:

x = int(sqrt(n)) = int(1.47...) = 1
c = x**2 - n = 1**2 - 2 = 1 - 2 = -1

对于平方根不是整数的n的值,很可能会发生这种情况。你知道吗

sqrt(n) >= int(sqrt(n)), n >= 0

然后,当调用sqrt(c)时,它超出了域,因为它不能处理负值。你知道吗

>>> from math import sqrt
>>> sqrt(-1)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: math domain error

你应该使用一些可以处理虚数的东西,例如^{}

或进行检查以确保不会发生这种情况:

举个例子。。。你知道吗

if c < 0:
    c = 0 

但是,一旦你解决了这个问题,你就会遇到另一个问题:

这是一个无限循环:

while (sqrt(c)!=int(sqrt(c))):
    x=x+1

您需要更新c,否则无论您增加x多少次,条件都不会改变。你可能是这个意思?你知道吗

while (sqrt(c)!=int(sqrt(c))):
    x=x+1
    c = x**2+n # < - UPDATE c

相关问题 更多 >

    热门问题