How to fix "ZeroDivisionError: float division by zero" - python

I have calcularBeta1 method. When I run the program, I've got this error:
ZeroDivisionError: float division by zero
resultadoB1 = (sumaXY - ((sumaX * sumaY ) / totalElementos )) / (sumaXCuadrada - math.pow(sumaX, 2) / totalElementos)
Method calcularBeta1
def calcularBeta1(self, lista):
actual = lista.nodoInicio
sumaXY = 0
sumaX = 0
sumaY = 0
sumaXCuadrada = 0
totalElementos = 0
while actual != None:
dato1 = actual.dato1
dato2 = actual.dato2
sumaXY += dato1 * dato2
sumaX += dato1
sumaY += dato2
sumaXCuadrada += math.pow(dato1, 2)
totalElementos += 1
actual = actual.siguienteNodo
resultadoB1 = (sumaXY - ((sumaX * sumaY ) / totalElementos )) / (sumaXCuadrada - math.pow(sumaX, 2) / totalElementos)
return resultadoB1
LecturaArchivo class
class LecturaArchivo:
datosArchivo = ListaEnlazada()
operaciones = Operaciones()
xTemporal = 0
yTemporal = 0
nombreArchivo = input('Nombre del archivo: ')
archivo = open(nombreArchivo, "r")
lineas = archivo.read()
datos = lineas.split(',')
datoProxy = float(input('Proxy: '))
while lineas:
lineas = archivo.readlines()
xTemporal = datos[0]
yTemporal = datos[1]
datosArchivo.agregarNodoFinal(float(xTemporal), float(yTemporal))
print(datos)
sumaElementos = sum(datosArchivo.obtenerNodos())
mediaElementos = operaciones.media(sumaElementos, datosArchivo.tamano())
beta1 = operaciones.calcularBeta1(datosArchivo)
print('Beta1: ', beta1)
beta0 = operaciones.calcularBeta0(beta1, media)
print('Beta0: ', beta0)
yk = operaciones.calcularYK(beta0, beta1, datoProxy)
print('Regresión Líneal: ', yk)

The ZeroDivisionError happens when you try to divide a number by 0, which as you know is a mathematical impossibility, just change the value of the dividend.

Python is unable to divide numbers by 0. If you ever attempt to divide by 0, python will throw a ZeroDivisionError, which is what happened to you. The best way to fix it is to just not divide by zero. You can use an if statement to ensure that the values are not zero.

Don't divide by zero.
In the expression it complains about
resultadoB1 = (sumaXY - ((sumaX * sumaY ) / totalElementos )) / (sumaXCuadrada - math.pow(sumaX, 2) / totalElementos)
it will be either totalElementos or the results of sumaXCuadrada - math.pow(sumaX, 2) that are zero.
You'll need to add code to handle the possibility of those situations before trying to calculate that formula.

Related

Python - While trying to calculate RSI(Relative strength index - stock indicator) my results are "upside down" and shifted

I am trying to calculate RSI using simple functions.
The general formula for it is:
RSI = 100/(1+RS), where RS = Exponential Moving Average of gains / -||- of losses.
Here is what I am getting:
enter image description here
Here it is how should it look like:
enter image description here
I have everything double checked or even triple checked, but I can't find any mistake.
Thus I need your help, I know that the question is very simple though I need some help, I have no idea where I have made the mistake.
The general idea of RSI is that it should be low where the price is "low" and high, where the price is high, and generally no matter what I try I have it upside down.
def EMA(close_price_arr, n):
a = (2/n + 1)
EMA_n = np.empty((1, len(close_price_arr)))
for i in range(len(close_price_arr)):
if i < n:
# creating NaN values where it is impossible to calculate EMA to drop it later after connecting the whole database
EMA_n[0, i] = 'NaN'
if i >= n:
# Calaculating nominator and denominator of EMA
for j in range(n):
nominator_ema += close_price_arr[i - j] * a**(j)
denominator_ema += a**(j)
EMA_n[0, i] = nominator_ema / denominator_ema
nominator_ema = 0
denominator_ema = 0
return EMA_n
def gains(close_price_arr):
gain_arr = np.empty((len(close_price_arr) - 1))
for i in range(len(close_price_arr)):
if i == 0:
pass
if i >= 1:
if close_price_arr[i] > close_price_arr[i - 1]:
gain_arr[i - 1] = (close_price_arr[i] - close_price_arr[i-1])
else:
gain_arr[i - 1] = 0
return gain_arr
def losses(close_price_arr):
loss_arr = np.empty((len(close_price_arr) - 1))
for i in range(len(close_price_arr)):
if i == 0:
pass
if i >= 1:
if close_price_arr[i] < close_price_arr[i - 1]:
loss_arr[i - 1] = abs(close_price_arr[i] - close_price_arr[i - 1])
else:
loss_arr[i - 1] = 0
return loss_arr
def RSI(gain_arr, loss_arr, n):
EMA_u = EMA(gain_arr, n)
EMA_d = EMA(loss_arr, n)
EMA_diff = EMA_u / EMA_d
x,y = EMA_diff.shape
print(x, y)
RSI_n = np.empty((1, y))
for i in range(y):
if EMA_diff[0, i] == 'NaN':
RSI_n[0, i] = 'NaN'
print(i)
else:
RSI_n[0, i] = 100 / (1 + EMA_diff[0, i])
return RSI_n
#contextmanager
def show_complete_array():
oldoptions = np.get_printoptions()
np.set_printoptions(threshold=np.inf)
try:
yield
finally:
np.set_printoptions(**oldoptions)
np.set_printoptions(linewidth=3000)
pd.set_option('display.max_columns', None)
# Specyfying root folder, file folder and file
FILE = 'TVC_SILVER, 5.csv'
FOLDER = 'src'
PROJECT_ROOT_DIR = '.'
csv_path = os.path.join(PROJECT_ROOT_DIR, FOLDER, FILE)
# reading csv
price_data = pd.read_csv(csv_path, delimiter=',')
price_data_copy = price_data.copy()
price_data_nodate = price_data.copy().drop('time', axis=1)
price_data_np = price_data_nodate.to_numpy(dtype='float32')
close_price = price_data_np[:, 3]
EMA15 = EMA(close_price_arr=close_price, n=15)
EMA55 = EMA(close_price_arr=close_price, n=55)
gain = gains(close_price_arr=close_price)
loss = losses(close_price_arr=close_price)
RSI14 = RSI(gain_arr=gain, loss_arr=loss, n=14)
Try this:
"""dataset is a dataframe"""
def RSI(dataset, n=14):
delta = dataset.diff()
dUp, dDown = delta.copy(), delta.copy()
dUp[dUp < 0] = 0
dDown[dDown > 0] = 0
RolUp = pd.Series(dUp).rolling(window=n).mean()
RolDown = pd.Series(dDown).rolling(window=n).mean().abs()
RS = RolUp / RolDown
rsi= 100.0 - (100.0 / (1.0 + RS))
return rsi

Can we solve Fractional Knapsack Problem by DP?

I know the Greedy approach is the best solution, but I'm so curious.
here is some of my code ...
def fractional_knapsack_dp2():
global resValue
# 각 size W를 넘지 않는 상태에서, i개의 아이템을 담은 상태에서 최대 profit을 담는 배열
P = [ [0 for x in range(W+1)] for x in range(n+1)] # [n+1][W+1] 0으로 초기화
for i in range(n+1):
currWeight = 0
for w in range(W+1):
if i==0 or w==0: # 0행 또는 0열은 skip
P[i][w] = 0;
elif weights[i-1] <= w:
currWeight = weights[i-1]
P[i][w] = max( values[i-1] + P[i-1][w - weights[i-1]], P[i-1][w] )
else:
# weight 1 단위로 설정 ... dksl d어케함 ;;
frac = 1 / weights[i-1]
if ( frac*values[i-1] + P[i-1][w - 1] > P[i-1][w] ) :
P[i][w] = P[i-1][w-1]
for k in range(w - currWeight) :
currWeight += 1
P[i][w] += frac*values[i-1]
else :
P[i][w] = P[i-1][w]
resValue = P[n][W]
I don't know how can I solve the problem.
Should I make another recurrence relation or array? 😢
I didn't learn about Dynamic Programming yet.

Scipy minimization one variable while keeping some variables constant - args defining problem

I have a function where I need to minimize c_init to make totalF output zero. the problem is that I have some constants over this function which are Es, f_slong and f_c. I need to repeat this whole minimization for 30 different cases meaning that I have 30 different constant variables and 30 different c_init initial values. Then, my aim is to obtain what the values for c_init will be at the end of the algorithm. However, those constant variables give me trouble. I do not have any inequality (I am not sure if I have to define it anyway), I strongly feel that my problem is to define the location and inputs of *args, I've tested out many different scenarios but they all failed. Could anyone help me out? Those constant variables should be coming from their list of array in every iteration and sending through the minimization function.
def c_neutral_un(c_init, Es, f_slong, f_c):
eps_s = e_cu_un * (d - c_init) / c_init
eps_s_prime = e_cu_un * (c_init - d_prime) / c_init
if Es * eps_s > f_slong:
f_s = f_slong
else:
f_s = Es * eps_s
if Es * eps_s_prime > f_slong:
f_s_prime = f_slong
else:
f_s_prime = Es * eps_s_prime
T = As * f_s
Cs_prime = As_prime * (f_s_prime - alfa1 * f_c)
Cc_conc = alfa1 * f_c * b * beta1 * c_init
totalF = Cc_conc + Cs_prime - T
return totalF
c = []
for i in range(31)
bnd = ([0, 200])
x0 = c_init[i]
Es = Es[i]
f_slong = f_slong[i]
f_c = f_c[i]
res = minimize(c_neutral_un, x0, args=([Es, f_slong, f_c], True) method = "SLSQP", bounds = bnd)
c.append(res.x)
THere is an error for constant assignment like Es = Es[i]
def c_neutral_un(c_init, Es, f_slong, f_c):
eps_s = e_cu_un * (d - c_init) / c_init
eps_s_prime = e_cu_un * (c_init - d_prime) / c_init
if Es * eps_s > f_slong:
f_s = f_slong
else:
f_s = Es * eps_s
if Es * eps_s_prime > f_slong:
f_s_prime = f_slong
else:
f_s_prime = Es * eps_s_prime
T = As * f_s
Cs_prime = As_prime * (f_s_prime - alfa1 * f_c)
Cc_conc = alfa1 * f_c * b * beta1 * c_init
totalF = Cc_conc + Cs_prime - T
return totalF
c = []
for i in range(31):
bnd = ([0, 200])
x0 = c_init[i]
Es2 = Es[i]
f_slong2 = f_slong[i]
f_c2 = f_c[i]
res = minimize(c_neutral_un, x0, args=([Es2, f_slong2, f_c2], True),method = "SLSQP", bounds = bnd)
c.append(res.x)

FloatingPointError: overflow encountered in double_scalars

I've set up numpy.seterr as follows:
np.seterr(invalid='raise', over ='raise', under='raise')
And I'm getting the following error:
c = beta[j,i] + oneminusbeta[j,i]
FloatingPointError: overflow encountered in double_scalars
I've checked what beta[j,i] and oneminusbeta[j,i] are at the point of crash, and these are their values:
beta: -131.340389182
oneminusbeta: 0.0
Please note, this line of addition (beta[j,i] + oneminusbeta[j,i]) has run for thousands of lines in a loop (that performs image classification) before crashing here at this point.
How can I deal with this? Is it necessary to change the type of the numpy arrays?
This is how I've initialized them:
beta = np.empty([m,n])
oneminusbeta = np.empty([m,n])
Is it possible to cast the individual values before adding them up? Rather than changing the entire array declarations? Or is this even a serious issue? Would it be safe to simply turn off the numpy.seterr configuration and let the calculations go ahead without raising the error?
Edit
Someone suggested below, and I suspected as well, that the values being added shouldn't cause an overflow. Then how can I find out where the overflow is really happening?
This is my code:
epthreshold = 709
enthreshold = -708
f.write("weights["+str(i)+", " + str(j)+"] = math.exp(beta: " +str(beta[j,i])+ " + oneminusbeta: " + str(oneminusbeta[j,i])+")\n" )
c = beta[j,i] + oneminusbeta[j,i]
weights[i,j] = math.exp(np.clip(c, enthreshold, epthreshold))
And when I check my log file, this is the line I get:
weights[5550, 13] = math.exp(beta: -131.340389182 + oneminusbeta: 0.0)
Edit 2
Here's the rest of my code, where variables n,m and H have already been initialized to integer values:
import numba
import numpy as np
import statsmodels.api as sm
weights = np.empty([n,m])
for curr_n in range(n):
for curr_m in range(m):
weights[curr_n,curr_m] = 1.0/(n)
beta = np.empty([m,n])
oneminusbeta = np.empty([m,n])
for curr_class in range(m):
for curr_sample in range(n):
beta[curr_class,curr_sample] = 1./m
epthreshold = 709 # positive exponential threshold
enthreshold = -708
for h in range(H):
print "Boosting round %d ... " % h
z = np.empty([n,m])
for j in range(m): # computing working responses and weights, Step 2(a)(i)
for i in range(no_samples):
i_class = y[i] #get the correct class for the current sample
if h == 0:
z[i,j] = (int(j==i_class) - beta[j,i])/((beta[j,i])*(1. - beta[j,i]))
weights[i,j] = beta[j,i]*(1. - beta[j,i])
else:
if j == i_class:
z[i,j] = math.exp(np.clip(-beta[j,i],enthreshold, epthreshold))
else:
z[i,j] = -math.exp(np.clip(oneminusbeta[j,i], enthreshold, epthreshold))
f.write("weights["+str(i)+", " + str(j)+"] = math.exp(beta: " +str(beta[j,i])+ " + oneminusbeta: " + str(oneminusbeta[j,i])+")\n" )
c = beta[j,i] + oneminusbeta[j,i]
weights[i,j] = math.exp(np.clip(c, enthreshold, epthreshold))
g_h = np.zeros([1,1])
j = 0
# Calculating regression coefficients per class
# building the parameters per j class
for y1_w in zip(z.T, weights.T):
y1, w = y1_w
temp_g = sm.WLS(y1, X, w).fit() # Step 2(a)(ii)
if np.allclose(g_h,0):
g_h = temp_g.params
else:
g_h = np.c_[g_h, temp_g.params]
j = j + 1
if np.allclose(g,0):
g = g_h
else:
g = g + g_h # Step(2)(a)(iii)
# now set g(x), function coefficients according to new formula, step (2)(b)
sum_g = g.sum(axis=1)
for j in range(m):
diff = (g[:,j] - ((1./m) * sum_g))
g[:,j] = ((m-1.)/m) * diff
g_per_round[h,:,j] = g[:,j]
#Now computing beta, Step 2(c)...."
Q = 0.
e = 0.
for j in range(m):
# Calculating beta and oneminusbeta for class j
aj = 0.0
for i in range(no_samples):
i_class = y[i]
X1 = X[i].reshape(1, no_features)
g1 = g[:,j].reshape(no_features, 1)
gc = g[:,i_class].reshape(no_features, 1)
dot = 1. + float(np.dot(X1, g1)) - float(np.dot(X1,gc))
aj = dot
sum_e = 0.
a_q = []
a_q.append(0.)
for j2 in range(m): # calculating sum of e's except for all j except where j=i_class
if j2 != i_class: # g based on j2, not necessarily g1?
g2 = g[:,j2].reshape(no_features, 1)
dot1 = 1. + float(np.dot(X1, g2)) - float(np.dot(X1,gc))
e2 = math.exp(np.clip(dot1,enthreshold, epthreshold))
sum_e = sum_e + e2
a_q.append(dot1)
if (int(j==i_class) == 1):
a_q_arr = np.array(a_q)
alpha = np.array(a_q_arr[1:])
Q = mylogsumexp(f,a_q_arr, 1, 0)
sumalpha = mylogsumexp(f,alpha, 1, 0)
beta[j,i] = -Q
oneminusbeta[j,i] = sumalpha - Q
else:
alpha = a_q
alpha = np.array(alpha[1:])
a_q_arr = np.array(a_q)
Q = mylogsumexp(f,a_q_arr, 0, aj)
sumalpha = log(math.exp(np.clip(Q, enthreshold, epthreshold)) - math.exp(np.clip(aj, enthreshold, epthreshold)))
beta[j,i] = aj - Q
oneminusbeta[j,i] = sumalpha - Q
and the function mylogsumexp is:
def mylogsumexp(f, a, is_class, maxaj, axis=None, b=None):
np.seterr(over="raise", under="raise", invalid="raise")
threshold = -sys.float_info.max
maxthreshold = sys.float_info.max
epthreshold = 709 # positive exponential threshold
enthreshold = -708
a = asarray(a)
if axis is None:
a = a.ravel()
else:
a = rollaxis(a, axis)
if is_class == 1:
a_max = a.max(axis=0)
else:
a_max = maxaj
#bnone = " none "
if b is not None:
a_max = maxaj
b = asarray(b)
if axis is None:
b = b.ravel()
else:
b = rollaxis(b, axis)
a = np.clip(a - a_max, enthreshold, epthreshold)
midout = np.sum(np.exp(a), axis=0)
midout = 1.0 + np.clip(midout - math.exp(a_max), threshold, maxthreshold)
out = np.log(midout)
else:
a = np.clip(a - a_max, enthreshold, epthreshold)
out = np.log(np.sum(np.exp(a)))
out += a_max
if out == float("inf"):
out = maxthreshold
if out == float("-inf"):
out = threshold
return out

FEniCS: UMFPACK reports that the matrix being solved is singular

I created a divided domain with the stokes-equation in the first subdomain and the mixed-poisson-equation (darcy) in the second subdomain. I work with the UnitSquare and the subdomain 1 should be the interval from 0 to 0,5 and the subdomain 2 from 0,5 to 1.
But now i get the following error:
Solving linear variational problem.
UMFPACK problem related to call to numeric
* Warning: UMFPACK reports that the matrix being solved is singular.
UMFPACK problem related to call to solve
* Warning: UMFPACK reports that the matrix being solved is singular.
assert vmax>=vmin, "empty range, please specify vmin and/or vmax"
Assertion error: empty range, please specify vmin and/or vmax
Can anyone help?
Thanks!
Here is the code:
enter code here
#-*- coding: utf-8 -*-
from dolfin import *
import numpy as np
# Define mesh
mesh = UnitSquare(32,32)
#Subdomain 1
# Gitter übergeben
subdomains = CellFunction("uint", mesh)
# Klasse des Teilgebiets
class Domain_1(SubDomain):
def inside(self, x, on_boundary):
return between(x[0], (0, 0.5)) # Koordinatenangabe des Teilgebiets
# Objekt der Klasse erstellen
sub_domain1 = Domain_1()
sub_domain1.mark(subdomains,0)
# Definition Funktionenräume
U = FunctionSpace(mesh, "CG", 2)
V = FunctionSpace(mesh, "CG", 1)
W = U*V
# Definition Trial- und Testfunktion
(u, p) = TrialFunctions(W)
(v, q) = TestFunctions(W)
# boundary condition
p_in = 1
p_out = 0
noslip = DirichletBC(W.sub(0), (0),
"on_boundary && \
(x[1] <= DOLFIN_EPS | x[1] >= 0.5-DOLFIN_EPS)")
inflow = DirichletBC(W.sub(1), p_in, "x[0] <= 0.0 + DOLFIN_EPS*1000")
outflow = DirichletBC(W.sub(1), p_out, "x[0] >= 0.5 - DOLFIN_EPS*1000")
bcp = [noslip,inflow, outflow]
# Definition f
f = Expression("0")
# Variationsformulierung
a = inner(grad(u), grad(v))*dx + div(v)*p*dx(0) + q*div(u)*dx(0)
L = inner(f,v)*dx(0)
# Lösung berechnen
w = Function(W)
problem = LinearVariationalProblem(a, L, w, bcp)
solver = LinearVariationalSolver(problem)
solver.solve()
(u, p) = w.split()
# Subdomain 2
# Gitter übergeben
subdomains = CellFunction("uint", mesh)
# Klasse des Teilgebiets
class Domain_2(SubDomain):
def inside(self,x,on_boundary):
return between(x[0], (0.5,1.0)) # Koordinatenangabe des Teilgebiets
# Objekt der Klasse erstellen
sub_domain2 = Domain_2()
sub_domain2.mark(subdomains,1)
# Define function spaces and mixed (product) space
BDM = FunctionSpace(mesh, "BDM", 1)
DG = FunctionSpace(mesh, "DG", 0)
CG = FunctionSpace(mesh, "CG", 1)
W = MixedFunctionSpace([BDM, DG, CG])
# Define trial and test functions
(sigma, u, p) = TrialFunctions(W)
(tau, v, q) = TestFunctions(W)
#Define pressure boundary condition
p_in = 1
p_out = 0
noslip = DirichletBC(W.sub(1), (0),
"on_boundary && \
(x[1] <= 0.5 + DOLFIN_EPS | x[1] >= 1.0-DOLFIN_EPS)")
inflow = DirichletBC(W.sub(2), p_in, "x[0] <= 0.5 + DOLFIN_EPS*1000")
outflow = DirichletBC(W.sub(2), p_out, "x[0] >= 1.0 - DOLFIN_EPS*1000")
bcp = [noslip,inflow, outflow]
# Define f
#f = Expression("0")
f = Expression("10*exp(-(pow(x[0] - 0.5, 2) + pow(x[1] - 0.5, 2)) / 0.02)")
# Define variational form
a = (dot(sigma, tau) + div(tau)*u + div(sigma)*v)*dx(1) + inner(p,q)*dx(1) + u*q*dx(1)
L = f*v*dx(1)
# Compute solution
w = Function(W)
problem = LinearVariationalProblem(a, L, w, bcp)
solver = LinearVariationalSolver(problem)
solver.solve()
(sigma, u, p) = w.split()
# plot
plot(u, axes = True, interactive=True, title = "u")
plot(p, axes = True, interactive=True, title = "p")
I forgot the dx(0) in this term. But this was not the problem.
In the first part of the code (Stokes) I tried to write the no slip condition in the following way:
# Randbedingungen
def top_bottom(x, on_boundary):
return x[1] > 1.0 - DOLFIN_EPS or x[1] < DOLFIN_EPS
noslip = Constant((0.0,0.0))
bc0 = DirichletBC(W.sub(0), noslip, top_bottom)
p_in = 1
p_out = 0
inflow = DirichletBC(W.sub(1), p_in, "x[0] <= 0.0 + DOLFIN_EPS*1000")
outflow = DirichletBC(W.sub(1), p_out, "x[0] >= 0.5 - DOLFIN_EPS*1000")
bcp = [bc0, inflow, outflow]
# Definition f
f = Expression("(0.0, 0.0)")
# Variationsformulierung Stokes
a = inner(grad(u), grad(v))*dx(0) + div(v)*p*dx(0) + q*div(u)*dx(0)
L = inner(f,v)*dx(0)
But now I get the following error:
Shape mismatch: line 56, in <module> L = inner(f,v)*dx(0
Can anyone help? Thanks!
I think there are several mistakes here. In the first part of the code I think you are using Taylor-Hood elements to solve Stokes equation. If this us the case, then U should be:
U = VectorFunctionSpace(mesh, "CG", 2)
Also in this part of the code:
a = inner(grad(u), grad(v))*dx + div(v)*p*dx(0) + q*div(u)*dx(0)
L = inner(f,v)*dx(0)
I don't know why you are not using dx(0) for the first term. I encourage you to look at the demos at: http://fenicsproject.org/documentation/dolfin/dev/python/demo/index.html
You might get some more tips.

Categories