Sum of Fibonacci sequence throws overflow error for large numbers - python-3.x

For smaller numbers, till r = 1472 the below code is working well and good.
Code:
import math
def fib(n):
s5 = math.sqrt(5)
phi = (1 + s5) / 2;
return int(round(pow(phi, n) / s5));
def calculateSum(l, r):
# Using our deduced result
sum = fib(r + 2) - fib(l + 1)
res = sum % 1000000007
return res
l = 5
r =1400
print(calculateSum(l,r))
But when the r goes beyond 1473 it throws the following error.
Traceback (most recent call last):
File "C:/Users/HP/PycharmProjects/spoj/FIBOSUM.py", line 20, in <module>
print(calculateSum(l,r))
File "C:/Users/HP/PycharmProjects/spoj/FIBOSUM.py", line 14, in calculateSum
sum = fib(r + 2) - fib(l + 1)
File "C:/Users/HP/PycharmProjects/spoj/FIBOSUM.py", line 9, in fib
return int(round(pow(phi, n) / s5));
OverflowError: (34, 'Result too large')
Process finished with exit code 1
And I referred and searched about this error and found a way to mitigate using this link Error 34, Result too large. These changes are reflected below
Code2:
import decimal
def fib(n):
s5 = decimal.Decimal(5).sqrt()
phi = (1 + s5) / 2;
return int(round(pow(phi, n) / s5));
def calculateSum(l, r):
# Using our deduced result
sum = fib(r + 2) - fib(l + 1)
res = sum % 1000000007
return res
l = 5
r =4500000
print(calculateSum(l,r))
These changes are works for the numbers approximately less than say r = 4550000 but a number larger than 5000000 throws the following error
Traceback (most recent call last):
File "C:/Users/HP/PycharmProjects/spoj/FIBOSUM.py", line 20, in <module>
print(calculateSum(l,r))
File "C:/Users/HP/PycharmProjects/spoj/FIBOSUM.py", line 14, in calculateSum
sum = fib(r + 2) - fib(l + 1)
File "C:/Users/HP/PycharmProjects/spoj/FIBOSUM.py", line 9, in fib
return int(round(pow(phi, n) / s5));
decimal.Overflow: [<class 'decimal.Overflow'>]
Could anybody help me to resolve this problem?

Related

OverflowError: (34, 'Result too large') in round function

I need to use the round function in my code because at a point the floats became too big and python can't handle them, so i simply implemented it like this:
def h(x, theta):
return theta[0] + theta[1] * x
def err(theta, x, y):
error = []
i = 0
for e in x:
prevision = h(x[i], theta) - y[i] #part where i putted round function
prevision = round(prevision, 10)
print(prevision)
error.append(prevision)
i += 1
return error
def sqrErr(error):
sqrError = []
for e in error:
sqrError.append(e ** 2)
return sqrError
def errForX(error, x):
errorForX = []
i = 0
for e in error:
errorForX.append(error[i] * x[i])
i += 1
return errorForX
def Theta(theta, error, sqrError, errorForX, lr):
newThetaList = []
i = 0
for e in theta:
newTheta = 0
if i == 0: #theta_0
newTheta = e - lr * (1/2) * sum(error) * ((1/4) * sum(sqrError))
elif i == 1: #theta:1
newTheta = e - lr *(1/2) * sum(errorForX) * ((1/4) * sum(sqrError))
newThetaList.append(newTheta)
i += 1
return newThetaList
def Train():
nLoops = 1000000
y =[5, 11, 21]
x = [2, 5, 10]
theta = [0, 0]
lr = 0.00021
prediction = []
for loop in range(nLoops):
error = err(theta, x, y)
sqrError = sqrErr(error)
errorForX = errForX(error, x)
theta = Theta(theta, error, sqrError, errorForX, lr)
predictions = []
for e in x:
predictions.append(h(e, theta))
print("Theta: ")
print(theta)
print("Targets: ")
print(y)
print("Predictions: ")
print(predictions)
Train()
The numbers became too big and it throws an error.
This is my first ever script of a machine learning algorithm, the squared error became a really long number and i don't how to prevent that, tried to limit to 10 the number of digits of the number that is going to be raised to the second but it didn't work
This is the error:
Traceback (most recent call last):
File "C:/Users/flama/OneDrive/Desktop/rete neurale v3.py", line 74, in <module>
Train()
File "C:/Users/flama/OneDrive/Desktop/rete neurale v3.py", line 59, in Train
sqrError = sqrErr(error)
File "C:/Users/flama/OneDrive/Desktop/rete neurale v3.py", line 21, in sqrErr
sqrError.append(e ** 2)
OverflowError: (34, 'Result too large')

Adding items to a deque() via a generator

I have a prime number generator. The yielded items are cast into a list. I can reference any item in the list.
def primes(limit):
yield 2
if limit < 3:
return
lmtbf = (limit - 3) // 2
buf = [True] * (lmtbf + 1)
for i in range((int(limit ** 0.5) - 3) // 2 + 1):
if buf[i]:
p = i + i + 3
s = p * (i + 1) + i
buf[s::p] = [False] * ((lmtbf - s) // p + 1)
for i in range(lmtbf + 1):
if buf[i]:
yield i + i + 3
x = list(primes(100))
print(x)
print(len(x), '\n')
Output:
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]
25
The problem is if I use x = list(primes(num)) with a very large number then the resultant list becomes
extremely large.
All I want are the last n (the largest) items in the list, but I would to be able to vary n.
I thought a deque() would be perfect for this. I was looking through documentation and I found: Appending to a deque that is full (len(d) == d.maxlen) discards items from the other end.
This, combined with the ability to specify a maxlen=n at queue creation is exactly what I want.
With that in mind, I tried this:
from collections import deque
def primes(limit):
yield 2
if limit < 3:
return
lmtbf = (limit - 3) // 2
buf = [True] * (lmtbf + 1)
for i in range((int(limit ** 0.5) - 3) // 2 + 1):
if buf[i]:
p = i + i + 3
s = p * (i + 1) + i
buf[s::p] = [False] * ((lmtbf - s) // p + 1)
for i in range(lmtbf + 1):
if buf[i]:
yield i + i + 3
x = deque([primes(100)], maxlen=10)
# x = list(primes(100))
print(x)
print(len(x), '\n')
But what I get is this:
deque([<generator object primes at 0x0000025ED8449C80>], maxlen=10)
1
I also tried:
for i in x:
print(x)
But that also does not work.
How can I use deque() as I described above to get my desired result?
I need to be able to print out the contents of the deque, which should be the last n items from the generator.
Figured it out: x = deque([x for x in primes(100)], maxlen=10)
deque([53, 59, 61, 67, 71, 73, 79, 83, 89, 97], maxlen=10)
10
x = deque([x for x in primes(1000)], maxlen=10)
deque([937, 941, 947, 953, 967, 971, 977, 983, 991, 997], maxlen=10)
10

Getting Integer division and modulo by zero error

I'm getting Integer Division or Modulo by zero error.
def getProduct(n):
product = 1
while (n != 0):
product = product * (n % 10)
n = n // 10
return product
def printSubstrings(n):
s=int(math.log10(n))
d=(math.pow(10,s))
k=d
count = 0
while n>0:
while d>0:
ans=0
ans = getProduct(n//d)
if ans%4==0 or ans%2!=0:
count+=1
d=int(d/10)
n = int(n%k)
k = int(k//10)
d = k
print(count)
Simple Inputs are running well but On entering Large input data it gives ZERODIVISIONERROR
on large input
10
11903030 2093524 04935049 09024 12242910 109310 1000901 103412 102901 10290191
Error I get:
Traceback (most recent call last):
File "e:/CodeWork/Code Challenge/rough.py", line 271, in <module>
printSubstrings(num)
File "e:/CodeWork/Code Challenge/rough.py", line 261, in printSubstrings
n = int(n%k)
ZeroDivisionError: integer division or modulo by zero
You need to make sure k != 0 holds before you compute n % k.
Since the modulus operator % is implemented by finding the remainder upon division, you will get a division by zero error if you try to evaluate n % 0 for any integer n.

I have implemented mergesort in python, but it gives me a "maximum recursion depth exceeded in comparison" error

I tried implementing mergesort in python, but on the "mergesort" function where I check if the sorting is done it gives me a maximum recursion depth exceeded in comparison error. I know that this means it repeats the function too much, but I have no idea what is causing it or how to fix it. I've tried tweaking some settings but nothing seems to work. Code and error is provided below.
def mergesort(arr, start, end):
if start > end:
return
middle = (start + end) // 2
mergesort(arr, start, middle)
mergesort(arr, middle + 1, end)
return merge(arr, start, end, middle)
def merge(arr, start, end, middle):
leftCopy = arr[start:middle]
rightCopy = arr[middle + 1:end]
leftIndex = 0
rightIndex = 0
sortedIndex = start
while leftIndex < len(leftCopy) and rightIndex < len(rightCopy):
if leftCopy[leftIndex] > rightCopy[rightIndex]:
arr[sortedIndex] = leftCopy[leftIndex]
leftIndex += 1
else:
arr[sortedIndex] = rightCopy[rightIndex]
rightIndex += 1
sortedIndex += 1
while leftIndex < len(leftCopy):
arr[sortedIndex] = leftCopy[leftIndex]
leftIndex += 1
sortedIndex += 1
while rightIndex < len(rightCopy):
arr[sortedIndex] = rightCopy[rightIndex]
rightIndex += 1
sortedIndex += 1
sample = [3, 1, 2]
mergesort(sample, 0, len(sample) - 1)
print(sample)
Error:
Traceback (most recent call last):
File "mergesort.py", line 43, in <module>
mergesort(sample, 0, len(sample) - 1)
File "mergesort.py", line 7, in mergesort
mergesort(arr, start, middle)
File "mergesort.py", line 7, in mergesort
mergesort(arr, start, middle)
File "mergesort.py", line 7, in mergesort
mergesort(arr, start, middle)
[Previous line repeated 995 more times]
File "mergesort.py", line 2, in mergesort
if start > end:
RecursionError: maximum recursion depth exceeded in comparison
Your base case does not cover when start==end (which it should: a 1-element list cannot be out of order); in that case, middle=start, so the first recursive call is identical to the current one -- hence the unending recursion.

In theano, why am I getting this theano.gradient.DisconnectedInputError when it's clearly connected?

Traceback (most recent call last):
File "/home/axoren1/SmokingDataProject/Rotation Test.py", line 40, in <module>
dJ = T.grad((R(n, t) - R(n, angles)).norm(2), t)
File "/usr/local/lib/python2.7/dist-packages/theano/gradient.py", line 529, in grad
handle_disconnected(elem)
File "/usr/local/lib/python2.7/dist-packages/theano/gradient.py", line 516, in handle_disconnected
raise DisconnectedInputError(message)
theano.gradient.DisconnectedInputError: grad method was asked to compute the gradient with respect to a variable that is not part of the computational graph of the cost, or is used only by a non-differentiable operator: Theta
What does this mean? Below is my code an an explanation for why I think this error is vacuous.
import numpy as np
import theano
import theano.tensor as T
import theano.tensor.nlinalg as Tn
n = 5
angles = 2 * np.pi * np.random.rand(n, 1)
def R(n, angles):
sines = T.sin(angles)
cosines = T.cos(angles)
def r(i, j):
sign = -1 * -1 ** ((i + j) % 2)
c = cosines[i - 1] * cosines[j]
s = T.prod(sines[i:j])
return sign * c * s
R = T.zeros((n, n))
for i in range(n):
for j in range(i, n):
T.inc_subtensor(R[i:i+1][j:j+1], r(i, j))
for i in range(0, n - 1):
T.inc_subtensor(R[i+1:i+2][i:i+1], sines[i])
return R
guess = np.random.rand(n, 1)
t = T.vector("Theta")
for i in range(100):
J = (R(n, t) - R(n, angles)).norm(2)
dJ = T.grad((R(n, t) - R(n, angles)).norm(2), t)
guess -= dJ.eval({t:guess})
print J.eval({t:guess}), guess
As you can see, the Theta node is defined and used by the cost function. I don't see how the function R is discontinuous at all. Why is this breaking?
The problem is that you need to assign the result of the inc_subtensor calls back to R.
Instead of
T.inc_subtensor(R[i:i+1][j:j+1], r(i, j))
and
T.inc_subtensor(R[i+1:i+2][i:i+1], sines[i])
use
R = T.inc_subtensor(R[i:i+1][j:j+1], r(i, j))
and
R = T.inc_subtensor(R[i+1:i+2][i:i+1], sines[i])
inc_subtensor is a symbolic operation that returns an object representing the symbolic result of incrementing the provided subtensor by the provided value.

Resources