scipy quad error "float division by zero" - scipy

Quick question, I want to integrate the following function :
def Kac(t):
frac1=1/((t**2-1)**2)
frac2=(((n+1)**2)*(t**(2*n)))/((t**(2*n+2)-1)**2)
return np.sqrt(frac1-frac2))
So I used
I=quad(Kac,-np.inf,np.inf)
But I got the error:
ZeroDivisionError: float division by zero
How can I avoid this?

Related

How can i initialize constant with derived values in HLSL?

I'm trying to migrate this glsl code into hlsl (unity shader). But the compiler complains about the following lines:
#define Length float
const Length m = 1.0;
const Length km = 1000.0 * m;
where km is derived from m, and the error msg said:
'km': initial value must be a literal expression
Is there any way to solve this without just replacing m with its literal value manually?
I tried to google this but found nothing related, or maybe this question is just a complaint about HLSL's weak compiler.
According to glsl-to-hlsl-reference, we should use static const qualifiers in hlsl.

How to overcome indefinite matrix error (NbClust)?

I'm getting the following error when calling NbClust():
Error in NbClust(data = ds[, sapply(ds, is.numeric)], diss = NULL, distance = "euclidean", : The TSS matrix is indefinite. There must be too many missing values. The index cannot be calculated.
I've called ds <- ds[complete.cases(ds),] just before running NbClust so there's no missing values.
Any idea what's behind this error?
Thanks
I had same issue in my research.
So, I had mailed to Nadia Ghazzali, who is the package maintainer, and got an answer.
I'll attached my mail and her reply.
my e-mail:
Dear Nadia Ghazzali. Hello Nadia. I have some questions about
NbClust function in R library. I have tried googling but could not
find satisfying answers. First, I’m so grateful for you to making
this awsome R library. It is very helpful for my reasearch. I tested
NbClust function in NbClust library with my own data like below.
> clust <- NbClust(data, distance = “euclidean”,
min.nc = 2, max.nc = 10, method = ‘kmeans’, index =”all”)
But soon, an error has occurred. Error: division by zero! Error in
Indices.WBT(x = jeu, cl = cl1, P = TT, s = ss, vv = vv) : object
'scott' not found So, I tried NbClust function line by line and
found that some indices, like CCC, Scott, marriot, tracecovw,
tracew, friedman, and rubin, were not calculated because of object
vv = 0. I’m not very familiar with argebra so I don’t know meaning
of eigen value. But it seems to me that object ss(which is squart of
eigenValues) should not be 0 after prodected.
So, here is my questions.
I assume that my data is so sparse(a lot of zero values) that sqrt(eigenValues) becomes too small, is that right? I’m sorry I
can’t attach my data but I can attach some part of eigenValues and
squarted eigenValues.
> head(eigenValues)
[1] 0.039769880 0.017179826 0.007011972 0.005698736 0.005164871 0.004567238
> head(sqrt(eigenValues))
[1] 0.19942387 0.13107184 0.08373752 0.07548997 0.07186704 0.06758134
And if my assume is right, what can I do for this problems? Only one
way to drop out 7 indices?
Thank you for reading and I’ll waiting your reply. Best regards!
and her reply:
Dear Hansol,
Thank you for your interest. Yes, your understanding is good.
Unfortunately, the seven indices could not be applied.
Best regards,
Nadia Ghazzali
#seni The cause of this error is data related. If you look at the source code of this function,
NbClust <- function(data, diss="NULL", distance = "euclidean", min.nc=2, max.nc=15, method = "ward", index = "all", alphaBeale = 0.1)
{
x<-0
min_nc <- min.nc
max_nc <- max.nc
jeu1 <- as.matrix(data)
numberObsBefore <- dim(jeu1)[1]
jeu <- na.omit(jeu1) # returns the object with incomplete cases removed
nn <- numberObsAfter <- dim(jeu)[1]
pp <- dim(jeu)[2]
TT <- t(jeu)%*%jeu
sizeEigenTT <- length(eigen(TT)$value)
eigenValues <- eigen(TT/(nn-1))$value
for (i in 1:sizeEigenTT)
{
if (eigenValues[i] < 0) {
print(paste("There are only", numberObsAfter,"nonmissing observations out of a possible", numberObsBefore ,"observations."))
stop("The TSS matrix is indefinite. There must be too many missing values. The index cannot be calculated.")
}
}
And I think the root cause of this error is the negative eigenvalues that seep in when the number of clusters is very high, i.e. the max.nc is high. So to solve the problem, you must look at your data. See if it got more columns then rows. Remove missing values, check for issues like collinearity & multicollinearity, variance, covariance etc.
For the other error, invalid clustering method, look at the source code of the method here. Look at line number 168, 169 in the given link. You are getting this error message because the clustering method is empty. if (is.na(method))
stop("invalid clustering method")

scipy dblquad providing the wrong result in simple double integral

I am trying to calculate a straightforward doble definite integral in Python: function Max(0, (4-12x) + (6-12y)) in the square [0,1] x [0,1].
We can do it with Mathematica and get the exact result:
Integrate[Max[0, 4-12*u1 + 6-12*u2], {u1, 0, 1}, {u2, 0,1}] = 125/108.
With a simple Monte Carlo simulation I can confirm this result. However, using scipy.integrate.dblquad I am getting a value of 0.0005772072907971, with error 0.0000000000031299
from scipy.integrate import dblquad
def integ(u1, u2):
return max(0, (4 - 12*u1) + (6 - 12*u2))
sol_int, err = dblquad(integ, 0, 1, lambda _:0, lambda _:1, epsabs=1E-12, epsrel=1E-12)
print("dblquad: %0.16f. Error: %0.16f" % (sol_int, err) )
Agreed that the function is not derivable, but it is continuous, I see no reason for this particular integral to be problematic.
I thought maybe dblquad has an 'options' argument where I can try different numerical methods, but I found nothing like that.
So, what am I doing wrong?
try different numerical methods
That's what I would suggest, given the trouble that iterated quad has on Windows. After changing it to an explicit two-step process, you can replace one of quad with another method, romberg seems the best alternative to me.
from scipy.integrate import quad, romberg
def integ(u1, u2):
return max(0, (4 - 12*u1) + (6 - 12*u2))
sol_int = romberg(lambda u1: quad(lambda u2: integ(u1, u2), 0, 1)[0], 0, 1)
print("romberg-quad: %0.16f " % sol_int)
This prints 1.1574073959987758 on my computer, and hopefully you will get the same.

How to save parts of linprog solutions

I am solving a serie of linear programing problems using linprog by indexing each problem in a for-loop:
from scipy.optimize import linprog
for i in range(1,N):
sol[i] = linprog(coa3[N][0], A_ub = coa4[i], b_ub = chvneg[i], options= {"disp": True})
I would like to save in a list (still indexed over i) the function minimization result and the array displaying the values of the variables. I guess I need to add in the for-loop something like minfval[i] = ??? and xval[i] = ???, but actually I don't know how to extract these values from the results provided by linprog. Any suggestions? Thanks a lot.
Consider reading the docs as it's pretty clearly explained what exactly linprog returns.
The good thing is, that you are actually storing these values with your code already because you are storing the whole scipy.optimize.OptimizeResult.
It's now just a matter of accessing it:
from scipy.optimize import linprog
for i in range(1,N):
sol[i] = linprog(coa3[N][0], A_ub = coa4[i], b_ub = chvneg[i], options= {"disp": True})
# iterate over solution-vectors
for i in range(1,N):
print(sol[i].x)
# iterate over objectives
for i in range(1,N):
print(sol[i].fun)
You should also check out the field success just to be safe!
Extraction of the docs (link above) on what is contained in linprog's result:
x : ndarray
The independent variable vector which optimizes the linear
programming problem.
fun : float
Value of the objective function.
slack : ndarray
The values of the slack variables. Each slack variable corresponds
to an inequality constraint. If the slack is zero, then the
corresponding constraint is active.
success : bool
Returns True if the algorithm succeeded in finding an optimal
solution.
status : int
An integer representing the exit status of the optimization::
0 : Optimization terminated successfully
1 : Iteration limit reached
2 : Problem appears to be infeasible
3 : Problem appears to be unbounded
nit : int
The number of iterations performed.
message : str
A string descriptor of the exit status of the optimization.

Swift: NSNumber is not a subtype of Float

I tried the code from Swift Programming Language in playground and got the following error "NSNumber is not a subtype of Float", I just modified it slightly by making x and y of type Float in struct Point. What am I missing?
If I added Float type to centerX and centerY, I got error: Could not find an overload for '/' that accepts the supplied arguments.
The error message is completely unrelated to the actual error... The actual error is cannot convert Double to Float.
In Size, x and y are Double (default type of float literal) but in Point, width and height are Float. They are different types and you can't mix them without explicit conversion.
There are number of ways to fix it. You can change them all to Double or Float.
e.g.
class Point
{
var x:Double
var y:Double
}
or you can convert them to correct type by doing Float(centerX)
ps: can you post the code next time so I can change it without retype them