python - Math domain error in fermat -
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 prime" return a, b
error:
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
i don't know going wrong program... me ?
most variable c going negative:
example
if call:
n = 2 fermatbook(n)
it assign following values following variables:
x = int(sqrt(n)) = int(1.47...) = 1 c = x**2 - n = 1**2 - 2 = 1 - 2 = -1
this happen alot on values of n
square root not integer.
sqrt(n) >= int(sqrt(n)), n >= 0
then when call sqrt(c)
out of domain because cannot handle negative values.
>>> math import sqrt >>> sqrt(-1) traceback (most recent call last): file "<stdin>", line 1, in <module> valueerror: math domain error
you should rather use can handle imaginary numbers, i.e. cmath
or perform checks assure not happen:
as example...
if c < 0: c = 0
as fix going run problem:
this infinite loop:
while (sqrt(c)!=int(sqrt(c))): x=x+1
you need update c otherwise condidtion never change no matter how many times increment x
. meant this?
while (sqrt(c)!=int(sqrt(c))): x=x+1 c = x**2+n # <--- update c
Comments
Post a Comment