Math domain error in fermat - 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
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 what is going wrong with the program... Could someone help me ?

most likely your variable c is going negative:
Example
if you call:
n = 2
fermatBook(n)
it will assign the following values to the following variables:
x = int(sqrt(n)) = int(1.47...) = 1
c = x**2 - n = 1**2 - 2 = 1 - 2 = -1
This will likely happen alot on values of n whose square root is not an integer.
sqrt(n) >= int(sqrt(n)), n >= 0
Then when you call sqrt(c) it is out of the domain because it cannot handle negative values.
>>> from math import sqrt
>>> sqrt(-1)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: math domain error
You should rather use something that can handle imaginary numbers, i.e. cmath
Or perform checks to assure this does not happen:
As an example...
if c < 0:
c = 0
As soon as you fix this however you are going to run into another problem:
This is an infinite loop:
while (sqrt(c)!=int(sqrt(c))):
x=x+1
you need to update c otherwise the condidtion will never change no matter how many times you increment x. You probably meant this?
while (sqrt(c)!=int(sqrt(c))):
x=x+1
c = x**2+n # <--- UPDATE c

Related

find the smallest square width but encounter modulo by zero error

I code such a function to find the smallest square of an land
def find_smallest(small, big):
if small == big:
return small
else:
sub_small = big % small
sub_big = small
find_smallest(sub_small, sub_big)
but it report error as
>>> find_smallest(640, 1280)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 7, in find_smallest
File "<stdin>", line 5, in find_smallest
ZeroDivisionError: integer division or modulo by zero
There is not a modulo by zero error.
What's the problem?
Consider find_smallest(2,8).
In the first loop you set sub_small = big % small = 8 % 2 = 0 and sub_big = small = 2. Then you call find_smallest(0,2).
In the second loop you then try to do sub_small = big % small = 2 % 0 which you cant do.

Programming a distance

First of all: I am by no means a Python expert, so this question is probably rather easy. Secondly, I worked over more than 2 hours on this and now I've decided I needed help. I want to implement a distance in Python. The distance is given as follows:
Where ui and uj are vectors that are given. d is the dimension of that vector. For example: if ui = (1,2,3), then ui_0= 1.
Now, this is what I've come up with so far: (here, xi = ui and xj = uj)
def dist(xi, xj, k):
distances = np.zeros(len(xi))
min1 = (0, 0)
min2 = (0, 0)
for dim in [0, len(xi)]:
for s in [-k, k]:
min1 = abs(xi[dim] - xj[dim + s])
min1[-k, k].min()
min2 = min(abs(xj[dim] - xi[dim + s]))
min2[-k, k].min()
distances = max(min1,min2)
but it doesn't work. Does anybody know where I've gone wrong?
Traceback:
Traceback (most recent call last): File "<input>", line 1, in
<module> File "<input>", line 8, in dist IndexError: invalid index
to scalar variable.
EDIT:
Ok, I tried to look at the case where k is maximal and I've taken the comments of Riley and Wouda into account. I came up with this piece of code:
def dist1(xi, xj):
for dim in range(len(xi)):
for s in range(-dim, len(xi) - dim):
return max(min(abs(xi[dim] - xj[dim + s])), min(abs(xj[dim] - xi[dim + s])))
and I still get the error:
Traceback (most recent call last):
File "<input>", line 1, in <module>
File "<input>", line 4, in dist1
TypeError: 'numpy.int64' object is not iterable
What is going on?
You appear to forget d is a parameter also (since you compute Dist_d^{ij}, where d is clearly a passed parameter). Together with k, I think the following represents the snippet of math you posted.
def dist(xi, xj, d, k):
min1 = min(abs(xi[d] - xj[d + s]) for s in range(-k, k + 1))
min2 = min(abs(xj[d] - xi[d + s]) for s in range(-k, k + 1))
return max(min1, min2)
Notice that Python will index negative values from the end of the list, which may or may not be what you want (in math, generally, not). So getting the arguments to this function right is a bit tricky, and you should build-in some checks to make sure all cases are handled correctly.

Python Queuing integer division error

import math
import random
m = 1.5 #mu
l = 2 #lambda
c = 3 #control/number of servers
def single(m, l, c):
p = (l/m)
Po = (1-(l/m))
Ls = (l/(m-l))
Ws = (1/(m-l))
Wq = (l/(m*(m-l)))
Lq = (l**2/(m*(m-l)))
return(p, Po, Ls, Ws, Wq, Lq)
def multi(m, lm, mu):
rho=lm/mu
n=0
sm=0
while(n<=m-1):
sm=(1/math.factorial(n))*pow(rho,n)
n+=1
sm = sm + 1/(1/math.factorial(m))*(pow(rho,m)*m*mu/(m*mu-lm))
lS=lm*mu*pow(rho,m)/((math.factorial(m-1)*(m*mu-lm)**2))*(1/sm)+rho
lQ=lS-rho
#Po = 1/sm
return(lq, ls)
singReturn=single(m, l, c)
multiReturn=multi(3, 2, 1.5)
print("SINGLE SERVER QUEUEING")
print("-----------------------")
print("p: %4.4f \nPo: %4.4f \nLs: %4.4f \nWs: %4.4f \nWq: %4.4f \nLq: %4.4f"%singReturn)
I am being returned and error with:
Traceback (most recent call last):
File "/home/schnipdip/Desktop/final_part1_chris_herzog.py", line 35, in <module>
multiReturn=multi(3, 2, 1.5)
File "/home/_____/Desktop/final_part1_.py", line 28, in multi
sm = sm + 1/(1/math.factorial(m))*(pow(rho,m)*m*mu/(m*mu-lm))
ZeroDivisionError: integer division or modulo by zero
I am trying to find the value of SM and then convert it into the Po variable. The while loop is controlling how many servers there are by m(or c) - 1.
I changed the variables in the loop to see if the variable was being overwritten in memory by a previous value and not resetting for whatever reason. I'm sure that has nothing to do with it.
If you're using Python 2, it's probably due to this part:
... 1/(1/math.factorial(m)) ...
Logically, it doesn't make much sense: mathematically, 1/(1/x) is just a clumsy way to spell plain x. So I bet your code has a logical error there.
But, in Python 2, it also has a programming error: / applied to integers does truncating integer division in Python 2:
>>> import math
>>> m = 3
>>> math.factorial(m)
6
>>> 1 / math.factorial(m)
0
To prevent that, use, e.g., 1.0 instead of 1 to force float division:
>>> 1.0 / math.factorial(m)
0.16666666666666666

getting ZeroDivisionError: integer division or modulo by zero

I had written a simple pascal triangle code in python but I am getting a error
def factorial(n):
c=1
re=1
for c in range(n):
re = re * c;
return(re)
print "Enter how many rows of pascal triangle u want to show \n"
n=input();
i=1
c=1
for i in range(n):
for c in range(n-i-1):
print ""
for c in range(i):
a = factorial(i);
b = factorial(c);
d = factorial(i-c);
z = (a/(b*d));
print "%d" % z
print "\n"
ERROR:
Traceback (most recent call last):
File "/home/tanmaya/workspace/abc/a.py", line 19, in <module>
z = (a/(b*d));
ZeroDivisionError: integer division or modulo by zero
Your factorial() function returns 0 for any input because of how you defined your range.
The range builtin starts at 0 unless otherwise defined so:
for c in range(n):
re = re * c # no semicolons in Python
is doing:
re = re * 0
on the first iteration so for all subsequent iterations:
re = 0 * c
will always be 0
Start your range at 1 like so
for c in range(1, n):
re *= c # The *= operator is short hand for a = a * b
you can see this more explicityly:
>>> print(list(range(5)))
[0, 1, 2, 3, 4]
>>> print(list(range(1,5)))
[1, 2, 3, 4]
>>>
or instead of rolling your own function use the one that comes with Python:
>>> from math import factorial
>>> factorial(3)
6
Upon closer reading of your code it seems you tried to circumvent this by setting c = 1 outside your for loop. This is not going to work because the variables you declared outside the loop are being reassigned inside it.
ZeroDivisionError means that you were trying to divide or modulo, a number n with 0.
in your case, z = (a/(b*d)) resulted in z = (a/0)
Also, as #theB pointed out, your factorial function is incorrect.
Try fixing those.
Also, you don't really need ; in your code. It's usually the case we put ; when we want to make the code one liner.

"non-integer arg 1 for randrange()" in python libary

I use a randomizer to make random number from 5 to 10. Can't be so hard? I have used it previously on code (+2000 lines of code, too much for here) and no coding errors occurred.
My code is simply easter egg to my game but it broke all my code:
...
def slowp(t):
for l in t:
sys.stdout.write(l)
sys.stdout.flush()
x=random.randint(0.1,0.9)
time.sleep(x)
print("")
if act=="++++++++++[>+++++++>++++++++++>+++>+<<<<-]>++.>+.+++++++..+++.>++.<<+++++++++++++++.>.+++.------.--------.>+.>":
slowp("Hey, that is hello world made in brainfuck!")
...
act is a string whose value is provided by the user simply with act=str(input("type here.")). It is directly done before this part.
Error message:
Traceback (most recent call last):
File "startgame.py", line 2084, in <module>
slowp("Hey, that is hello world made in brainfuck!")
File "startgame.py", line 140, in slowp
x=random.randint(0.1,0.9)
File "/usr/lib/python3.4/random.py", line 216, in randint
return self.randrange(a, b+1)
File "/usr/lib/python3.4/random.py", line 180, in randrange
raise ValueError("non-integer arg 1 for randrange()")
ValueError: non-integer arg 1 for randrange()
What is the actual problem?
You are trying to pass floating point values to random.randint(). That function only takes integers.
You need to use the random.uniform() function instead; it'll produce a uniformly random value between the lower and upper bound (inclusive):
Return a random floating point number N such that a <= N <= b for a <= b and b <= N <= a for b < a.
Demo:
>>> import random
>>> random.uniform(0.1, 0.9)
0.6793304134926453
ValueError: non-integer arg 1 for randrange()
random.randint(0.1,0.9)
You have to pass integers to that function. 0.1 and 0.9 are not integers
you can
random.randint(1,9)/10
in random.randint(start, stop, step) we can use step
random.uniform(start, stop) - no step

Categories

Resources