ASKSAGE: Sage Q&A Forum - RSS feedhttps://ask.sagemath.org/questions/Q&A Forum for SageenCopyright Sage, 2010. Some rights reserved under creative commons license.Wed, 14 Jul 2021 12:35:41 +0200numeric precision unexpectedly lowhttps://ask.sagemath.org/question/58012/numeric-precision-unexpectedly-low/I try to integrate a probability density function over an fixed interval.
Can't give the like but it is a "relativistic Breit-Wigner Distribution" as in the English Wikipedia.
Gamma = 294000
m = 3686100
gamma = sqrt(m^2*(m^2+Gamma^2))
k = (2*sqrt(2)*m*Gamma*gamma)/(pi*sqrt(m^2+gamma))
BW = k/((x^2-m^2)^2+m^2*Gamma^2)
test = integrate(BW(x),x,m-20*Gamma,m+20*Gamma)
Till here I shouldn't have lost any precision. but when I convert it numerically with
n(test,2000)
I get:
1.003568780514681625312584816997550190541415598167450102773034501594600296432162707154049825083671452461581265874619355037287669117698123644188958803147725041330150928274806048238042399517154207573726037521427349383968841867335044816048064092169439887022730672979989338003256477687641391106254297483937686718675512005461848316884186358220468903611061147782405268579702217582451508116179810896698136112722502668649975423152214020083815884479176920571802765348290248949692543327981513253681778869531348343181499633971108206392658073359294594919457298263920263466439149236869382936665388139526661407807092
Since this is an integral over a probability density it must be less or equal to unity. To make things worse the test I used to catch this failed. When I print n(test,2000)-n(test,5000) I get:
1.548076368777034133563243683402305144019545879147318729129474813190957966982407215191933066512274489911906109674015771900520547143254593904332062734353178144359258512027924010153347526193868596270002650844292344493806124142870891743921764286481744814534440665865632030746674736110661609478466022255757297949839318763567151082721152805813677624313092475594710476219357188434129215184208643483256856632402761545583382935944646898012751255575740279260126952010697251536670906745564901191471261083975404910237568882848368855134234892724370503380053787304268124196831149676013601785994763640281219314046884e-517
So it seems as if 500 digits are correct. Is this a bug or am I not using this correctly? I'm using sage 9.0 as packaged in Ubuntu.just_tryin_to_use_thisWed, 14 Jul 2021 12:35:41 +0200https://ask.sagemath.org/question/58012/Incorrect result for integral of (cos z) / zhttps://ask.sagemath.org/question/57637/incorrect-result-for-integral-of-cos-z-z/I am confused by the following result: I'd like to integrate `cos(z) / z` on a circle around the origin. I tried:
var('z,t')
f = (cos(z))/z
show(f)
gamma = e^(i * t)
dg = gamma.diff(t)
h = f(z=gamma) * dg
print(h)
show(h.integrate(t, 0, 2 * pi))
and I get:
I*cos(e^(I*t))
0
If I put the same integral into [WolframAlpha](https://www.wolframalpha.com/input/?i=integral+of+I*cos%28e%5E%28I*t%29%29+from+t+%3D+0+to+2+*+pi), I get the result I was expecting (`2 pi i`).
Is this a bug, or have I specified the problem incorrectly?
ripple_carryMon, 21 Jun 2021 15:09:34 +0200https://ask.sagemath.org/question/57637/Tips for Symbolic Integration of Rational Functions?https://ask.sagemath.org/question/57028/tips-for-symbolic-integration-of-rational-functions/I am doing some work that requires me to do a lot of symbolic integration of rational functions over the interval [-1, 1]. These rational functions end up containing the integration variable, plus a few real symbolic parameters t1,...,tn. The issue is, as I add more parameters and things get more complicated, Sage's integrate function slows down a lot, and even occasionally seems to get completely stuck.
I am reasonably new to Sage, and my code is able to handle the simpler cases, so it might just be that these functions become too complicated to integrate as I add more parameters. But I'm wondering, are there any general things I could do that might make the integration a little easier/faster? For example, I tried calling .partial_fractions() on the integrand before passing it to the integrate function, but I didn't really notice much of an effect. If you can think of anything that might help speed up these computations, I would appreciate it.OgrelordSun, 09 May 2021 00:03:28 +0200https://ask.sagemath.org/question/57028/Integrating differential formshttps://ask.sagemath.org/question/56906/integrating-differential-forms/ I'd like to integrate `dx /\ dy` over the unit square. Naively, I would expect the following to work:
E.<x,y> = EuclideanSpace(2)
phi = E.diff_form(2)
phi[1, 2] = 1
show(integrate(integrate(phi, x, 0, 1), y, 0, 1))
but it fails with:
TypeError: unable to convert 2-form on the Euclidean plane E^2 to a symbolic expression
and I can't find anything about integration in the DiffFormFreeModule documentation. What is the right way to do this?ripple_carrySun, 02 May 2021 21:42:54 +0200https://ask.sagemath.org/question/56906/definite integral returns error but indefinite followed by equivalent subtraction does nothttps://ask.sagemath.org/question/56070/definite-integral-returns-error-but-indefinite-followed-by-equivalent-subtraction-does-not/Searching the other questions on definite integrals I did not find the same issue, maybe I missed it.
I use SageMath 9.2
When I define these variables:
var('x,y', domain='real')
var('c,p_i', domain='positive')
f_x_pi = 1/5*(3*c - 0.06)*(0.2969*sqrt(x/(c - 0.02)) - 0.126*x/(c - 0.02) - 0.3516*x^2/(c - 0.02)^2 + 0.2843*x^3/(c - 0.02)^3 - 0.1036*x^4/(c - 0.02)^4)
c_i_u = c - 0.02
This:
I = integrate(integrate((x^2+y^2),y,-f_x_pi,f_x_pi),x,0,c_i_u)
return a `Maxima requested additional constraints` error but this:
I_indef = integrate(integrate((x^2+y^2),y,-f_x_pi,f_x_pi),x)
I = I_indef(x=c_i_u) - I_indef(x=0)
or relying on `algorithm='sympy'`, which is slower, does not.
I am wondering if that's a bug and whether I should report it.louisgagTue, 09 Mar 2021 12:16:33 +0100https://ask.sagemath.org/question/56070/Definite Integral of loglikelihood function multipled by Gaussianhttps://ask.sagemath.org/question/55467/definite-integral-of-loglikelihood-function-multipled-by-gaussian/I am trying to calculate
definite_integral((-ln(2*pi)-ln(sigma)-1/2*((x-mu)/sigma)^2)*f, x, -infinity, infinity)
where
f=1/(sqrt(2*pi)*sigmaprime)*exp(-1/2*((x-muprime)/sigmaprime)^2)
using sagemath.
I have done `from sage.symbolic.integration.integral import definite_integral`
And I have also done
assume(sigma>0)
assume(sigmaprime>0)
however I obtain this error
ValueError: Computation failed since Maxima requested additional constraints; using the 'assume' command before evaluation *may* help (example of legal syntax is 'assume(muprime>0)', see `assume?` for more details)
Is muprime positive, negative or zero?
However muprime can be positive, negative or zero. So I don't know how to proceed.user2749584820Wed, 27 Jan 2021 12:51:41 +0100https://ask.sagemath.org/question/55467/How to do quantum mechanics integrals in Sage?https://ask.sagemath.org/question/54774/how-to-do-quantum-mechanics-integrals-in-sage/Hi.
I am a newcomer to Sage. I am trying to do integrals of the form shown below. This is from an introductory course in quantum mechanics.
$
\psi(x, t) = \int_{-\infty}^{+\infty} f(p) \psi_p(x - x_0, t) d\mathrm{p}
$
where,
$
\psi_p(x, t) = \dfrac{1}{\sqrt{2\pi\hbar}}e^\left( -\dfrac{i}{\hbar}\left(\dfrac{p^2}{2m}t - px \right)\right)
$
$
f(p) = \dfrac{1}{(2\pi)^{1/4} \sqrt{\sigma_p}}e^\left( -\dfrac{(p - p_0)^2}{4{\sigma_p}^2}\right)
$
I have tried the following in sage thus far:
forget()
var('x,t,p,p_0, m,h,x_0,sigma_p')
psi_p(x, t) = 1/(2*pi*h)^(1/2)*exp(-i/h*(p^2*t/(2*m) - p*(x - x_0)))
f(p) = 1/(2*pi)^(1/4)*1/sqrt(sigma_p)*exp(-(p - p_0)^2/(4*sigma_p^2))
show(psi_p(x, t))
show(f(p))
assume(m, 'constant')
assume(m > 0)
assume(h, 'constant')
assume(h > 0)
assume(p_0, 'constant')
assume(p_0 > 0)
assume(sigma_p, 'constant')
assume(sigma_p > 0)
assume(x, 'real')
assume(t, 'real')
from sage.symbolic.integration.integral import definite_integral
definite_integral(f(p)*psi_p(x, t), p, -oo, +oo)
Sage keeps complaining about requiring assumptions that I can't easily provide. Here is a sample output:
ValueError: Computation failed since Maxima requested additional constraints; using the 'assume' command before evaluation *may* help (example of legal syntax is 'assume(2*sigma_p^2*t
>0)', see `assume?` for more details)
Is 2*sigma_p^2*t
*sin(atan((2*sigma_p^2*t)/(h*m))
/2)
+h*m
*cos(atan((2*sigma_p^2*t)
/(h*m))
/2) positive, negative or zero?
My question: how would you do integrals like this in Sage? Is my fundamental approach correct?ARVSun, 20 Dec 2020 14:41:49 +0100https://ask.sagemath.org/question/54774/Triple integrals in a specific region of spacehttps://ask.sagemath.org/question/53419/triple-integrals-in-a-specific-region-of-space/Can I perform a triple integral in a region of space I define?
I'm trying to migrate from Mathematica to Sage,
and in Mathematica I could go and define a region of space
(with various limitations) and then perform the integral
of a function on it.
In Mathematica:
reg = ImplicitRegion[x + 2 y + 3 z < 2 && -1 < x < y < z < 1, {x, y, z}];
integral[{x, y, z} in reg, (x^2 + 2 y z)]
![mathematica-polyhedral-region-integrate-polynomial](/upfiles/16000472797455741.png)
Is there a way to easily perform this operation even in Sage?Teo7Sat, 12 Sep 2020 12:50:48 +0200https://ask.sagemath.org/question/53419/Problem evaluating a very tiny integralhttps://ask.sagemath.org/question/39514/problem-evaluating-a-very-tiny-integral/Hi everyone,
I'm pretty new with sage. I was forced to change from MATLAB to Sage, because I was told Sage does approximate very tiny numbers better as it can work with sqrt(2) as sqrt(2) and not as the rational number approximating it.
Approximations are very important for my problem. I need to evaluate this integral
$$\sum_{c=1}^{d}\int_{\min(256c-0.5,\frac{y(y+1)}{2})}^{\min(256c+0.5,\frac{y(y+1)}{2})}\frac{1}{\sqrt{2\pi}}e^{-\frac{x^2}{2}}\, dx$$
Suppose d = 1, then this is simply the integral
$$ \int_{255.5}^{256.5}\frac{1}{\sqrt{2\pi}}e^{-\frac{x^2}{2}}\, dx$$
To evaluate this integral I wrote the following code
> T = RealDistribution('gaussian,1)
> print T.cum_distribution_function(256.5)-T.cum_distribution_function(255.5)
because the integral above is the same as the difference of the distribution function of a standard distributed gaussian random variable between the boundaries of the integral.
However, and you can check yourselves if you don't believe it, the result I get with sage is 0.
I guess that this is due to some approximation, which sage does. Indeed the exact value of the integral is pretty close (and with pretty I mean a lot) to 0. My problem is that I need to be able to have the exact value, because the sum of integrals I'm working with and my whole work behind this integral requires me to be very careful with those little tiny numbers.
I tried to use the function
>integrate
to deal with this problem, but something funny and apparently inexplicable happened when I was trying to use it.
To be precise I defined this code:
def VarianceOfvy(y):
temp1 = 0
temp2 = 0
for r in range(0,y+1):
for x in range(0,r+1):
temp1 = temp1 + (255/256)^x * 1/256 * (r-x)^2
for r in range(0,y+1):
for x in range(0,r+1):
temp2 = temp2 + ((255/256)^x * 1/256 * (r-x))^2
sigma = temp1 - temp2
return sqrt(sigma)
def Integerd(y):
b = y*(y+1)/2
d = 1
c = 0
while min((c+1)*256-0.5,b) == (c+1)*256-0.5:
d = d+1
c = c+1
return d
def Probabilityvynequiv(y):
var('c')
b = (y*(y+1))/2
sigma = 2
mu = 1
d = Integerd(y)
factor = 1/(integrate(1/sqrt(2*pi)*e^(-(x/sigma)^2/2),x,-oo,(b-mu)/sigma) - integrate(1/sqrt(2*pi)*e^(-(x)^2/2),x,-oo,(-mu)/sigma))
p = sum(factor*1/sigma*integrate(1/sqrt(2*pi)*e^((-x^2)/(2)),x,c*256+0.5,min((c+1)*256-0.5,b)),c,0,d)
return p
And if I let it run, the result I get is
1/2*(erf(255.75*sqrt(2)) - erf(128.25*sqrt(2)) + erf(127.75*sqrt(2)) - erf(0.25*sqrt(2)))/(3*erf(1/4*sqrt(2)) + 1)
which I assume is correct, and at least it tells me that Sage is able to read my code and output a result.
If I call the function VarianceOfvy(2), the result I get is 3/65536*sqrt(11133895), which is also correct. Now, if I'm changing the command
sigma = 2
with
sigma = VarianceOfvy(2)
and try to let the whole program run again, Sage is not able anymore to output a result.
I'm really lost and I don't know what to do. Could someone advise me and give me some hints on how to evaluate those tiny integrals, in such a way that I don't loose any approximation?Alessandro VerzasconiMon, 13 Nov 2017 15:03:58 +0100https://ask.sagemath.org/question/39514/integration in sagemath 8.1https://ask.sagemath.org/question/53694/integration-in-sagemath-81/I executed the following,
def integral_R(f,a,b):
from sage.symbolic.integration.integral import definite_integral
return (definite_integral(f,x,a,b)).simplify_full()
alpha = 1/sqrt(3)
H = 2*arcsin(x/(sqrt(1-x^2)))
integral_R(H,0,alpha).n()
and got
1.16869906991626
The same integral in Wolfram Alpha
provides
0.38330
By inspection I know that Wolfram is right. What's wrong with sage math in the specific example?drazThu, 01 Oct 2020 23:30:40 +0200https://ask.sagemath.org/question/53694/Error in integralhttps://ask.sagemath.org/question/53172/error-in-integral/I've got this error on the second integral. I put the code on wxMaxima and returned sucessfull. On wxMaxima, raise a question "z is positive, negative or zero?", also on sage, but on sage I can't answer that. How can I correct this?
```x,y,z = var("x y z")```
```function = x*e^(-y)```
``` integral(function,y,0,ln(x)).integral(x,0,2*z) ```gabrielromao5Tue, 25 Aug 2020 15:50:58 +0200https://ask.sagemath.org/question/53172/Error during integration: not of type (UNSIGNED-BYTE 15)https://ask.sagemath.org/question/52913/error-during-integration-not-of-type-unsigned-byte-15/Hi everyone, I am new to Sage and coding, and I am trying to solve a tricky integral from equation 13 in this physics paper: www.nature.com/articles/srep11876
Here is the integrand in code form (I would upload a screenshot of the full equation, but I do not have enough karma points):
sage: var ('alpha beta E_o a d_o z_o n u')
(alpha, beta, E_o, a, d_o, z_o, n, u)
sage: j = CC.0
sage: integrand = e**(-j * n * u) / (((a + d_o + 0.5 * z_o * (((16 * pi) / (alpha * beta)) ** (-3))) + 0.5 * z_o * (((16 *
....: pi) / (alpha * beta)) ** (-3)) * sin(u)) ** 3) - 1
The integral is part of a Fourier coefficient, so it is a definite integral with limits -pi and pi. I want to integrate with respect to u and then solve the full equation for beta. All of the other variables are known.
However, when I try to integrate, I get an error:
sage: integrate(integrand, u, -pi, pi)
---------------------------------------------------------------------------
RuntimeError Traceback (most recent call last)
<ipython-input-32-84f9192f9549> in <module>()
----> 1 integrate(integrand, u, -pi, pi)
/opt/sagemath-9.1/local/lib/python3.7/site-packages/sage/misc/functional.py in integral(x, *args, **kwds)
751 """
752 if hasattr(x, 'integral'):
--> 753 return x.integral(*args, **kwds)
754 else:
755 from sage.symbolic.ring import SR
/opt/sagemath-9.1/local/lib/python3.7/site-packages/sage/symbolic/expression.pyx in sage.symbolic.expression.Expression.integral (build/cythonized/sage/symbolic/expression.cpp:64474)()
12434 R = ring.SR
12435 return R(integral(f, v, a, b, **kwds))
> 12436 return integral(self, *args, **kwds)
12437
12438 integrate = integral
/opt/sagemath-9.1/local/lib/python3.7/site-packages/sage/symbolic/integration/integral.py in integrate(expression, v, a, b, algorithm, hold)
929 return indefinite_integral(expression, v, hold=hold)
930 else:
--> 931 return definite_integral(expression, v, a, b, hold=hold)
932
933
/opt/sagemath-9.1/local/lib/python3.7/site-packages/sage/symbolic/function.pyx in sage.symbolic.function.BuiltinFunction.__call__ (build/cythonized/sage/symbolic/function.cpp:12262)()
1136 res = self._evalf_try_(*args)
1137 if res is None:
-> 1138 res = super(BuiltinFunction, self).__call__(
1139 *args, coerce=coerce, hold=hold)
1140
/opt/sagemath-9.1/local/lib/python3.7/site-packages/sage/symbolic/function.pyx in sage.symbolic.function.Function.__call__ (build/cythonized/sage/symbolic/function.cpp:6938)()
595 for i from 0 <= i < len(args):
596 vec.push_back((<Expression>args[i])._gobj)
--> 597 res = g_function_evalv(self._serial, vec, hold)
598 elif self._nargs == 1:
599 res = g_function_eval1(self._serial,
/opt/sagemath-9.1/local/lib/python3.7/site-packages/sage/symbolic/function.pyx in sage.symbolic.function.BuiltinFunction._evalf_or_eval_ (build/cythonized/sage/symbolic/function.cpp:13412)()
1224 res = self._evalf_try_(*args)
1225 if res is None:
-> 1226 return self._eval0_(*args)
1227 else:
1228 return res
/opt/sagemath-9.1/local/lib/python3.7/site-packages/sage/symbolic/integration/integral.py in _eval_(self, f, x, a, b)
203 for integrator in self.integrators:
204 try:
--> 205 A = integrator(*args)
206 except (NotImplementedError, TypeError, AttributeError):
207 pass
/opt/sagemath-9.1/local/lib/python3.7/site-packages/sage/symbolic/integration/external.py in maxima_integrator(expression, v, a, b)
44 result = maxima.sr_integral(expression,v)
45 else:
---> 46 result = maxima.sr_integral(expression, v, a, b)
47 return result._sage_()
48
/opt/sagemath-9.1/local/lib/python3.7/site-packages/sage/interfaces/maxima_lib.py in sr_integral(self, *args)
788 """
789 try:
--> 790 return max_to_sr(maxima_eval(([max_integrate],[sr_to_max(SR(a)) for a in args])))
791 except RuntimeError as error:
792 s = str(error)
/opt/sagemath-9.1/local/lib/python3.7/site-packages/sage/libs/ecl.pyx in sage.libs.ecl.EclObject.__call__ (build/cythonized/sage/libs/ecl.c:7794)()
803 """
804 lispargs = EclObject(list(args))
--> 805 return ecl_wrap(ecl_safe_apply(self.obj,(<EclObject>lispargs).obj))
806
807 def __richcmp__(left, right, int op):
/opt/sagemath-9.1/local/lib/python3.7/site-packages/sage/libs/ecl.pyx in sage.libs.ecl.ecl_safe_apply (build/cythonized/sage/libs/ecl.c:5456)()
375 if ecl_nvalues > 1:
376 s = si_coerce_to_base_string(ecl_values(1))
--> 377 raise RuntimeError("ECL says: {}".format(
378 char_to_str(ecl_base_string_pointer_safe(s))))
379 else:
RuntimeError: ECL says: 1.8189894035458565e-12 is not of type (UNSIGNED-BYTE 15).
I have no idea where 1.8189894035458565e-12 came from, and I get the same error after assigning values to all of the variables except beta and u.
Has anyone encountered this error before? Is there a better way I should evaluate this?lvb884Sat, 08 Aug 2020 06:03:34 +0200https://ask.sagemath.org/question/52913/Integration on a region defined by an inequalityhttps://ask.sagemath.org/question/44636/integration-on-a-region-defined-by-an-inequality/ Does Sage or Maxima have a routine for -directly- calculating an integral over a region defined implicitly by an inequality. Suppose region R is defined by "f(x,y) less than c" and we want to find "integral g(x,y) over R". Does Sage have a procedure for this? The required output will be a function of c.maesumiTue, 11 Dec 2018 16:47:56 +0100https://ask.sagemath.org/question/44636/what instance is integral from?https://ask.sagemath.org/question/43244/what-instance-is-integral-from/ When the result has `integrate` in it, I check for it as follows
sage: anti=integrate(1/(sqrt(x + 1)*sqrt(-x + 1) + 5), x)
integrate(1/(sqrt(x + 1)*sqrt(-x + 1) + 5), x)
sage: isinstance(anti.operator(), sage.symbolic.integration.integral.IndefiniteIntegral)
True
But the above does not work when the result is `integral` instead of `integrate`.
My question is, what instance is `integral` coming from?
sage: anti=integrate(cos(b*x + a)*cos_integral(d*x + c)/x,x, algorithm="fricas")
integral(cos(b*x + a)*cos_integral(d*x + c)/x, x)
sage: anti.operator()
integral
sage: isinstance(anti.operator(), sage.symbolic.integration.integral.IndefiniteIntegral)
False
I looked at http://doc.sagemath.org/html/en/reference/calculus/sage/symbolic/integration/integral.html
but still do not know how to check for `intergal` vs. `integrate`
Any suggestions?
thanks
--Nasser
NasserFri, 03 Aug 2018 05:26:05 +0200https://ask.sagemath.org/question/43244/Definite Integral Fails due to Runtime Errorhttps://ask.sagemath.org/question/39354/definite-integral-fails-due-to-runtime-error/Here is the code that I have been writing; it's meant to predict the moment of inertia of a perfect cylinder tilted and offset from its axis of rotation, among other things. However, the definite_integral command fails with an error thrown by the gcd function. I suspect the issue is due to Sage's inner workings; however, I do not have the time or know-how to fully debug this issue. Any help would be appreciated.
from sage.symbolic.integration.integral import definite_integral
from sage.calculus.integration import numerical_integral
dSpringStretchedFully=10.625
dSpringUnstretchedLength=7.875
dArmatureInches=8
dSpringAnchor=4.75
thetaArmatureDefault=95
dSpringPitch=dSpringUnstretchedLength/sin(thetaArmatureDefault*pi/180)*sin(pi/180*(180-thetaArmatureDefault-(180/pi*arcsin(dSpringAnchor*sin(thetaArmatureDefault*pi/180)/dSpringUnstretchedLength))))
fSpringPoundsPerInch=65.69
kNewtonsPerPound=4.44822
kMetersPerInch=0.0254
fSpringNewtonsPerInch=fSpringPoundsPerInch*kNewtonsPerPound
dArmatureMeters=dArmatureInches*kMetersPerInch
dHalfRopeInches=dArmatureInches*cos(pi/180*(thetaArmatureDefault-90))
dHalfRopeMeters=dHalfRopeInches*kMetersPerInch
fSpringNewtonsPerMeter=fSpringNewtonsPerInch/kMetersPerInch
fSpringMinimumLoad=0
kSpringDirection=1
rRopeInches=0.5
rRopeMeters=rRopeInches*kMetersPerInch
var('x')
var('dHalfRope')
var('thetaArmatureToRope')
thetaPointToAxis(x,thetaArmatureToRope)=thetaArmatureToRope-(180/pi*arctan((x-rRopeMeters)/dArmatureMeters))
dPointFromFarAxis(x,dHalfRope)=((dHalfRope^2)+(x-rRopeMeters)^2)^(1/2)
dPointFromNearAxis(x,dHalfRope,thetaArmatureToRope)=((dArmatureMeters^2)+((dPointFromFarAxis(x,dHalfRope))^2)-2*dPointFromFarAxis(x,dHalfRope)*dArmatureMeters*cos(pi/180*thetaPointToAxis(x,thetaArmatureToRope)))^(1/2)
IMultiplier(x)=2*(((rRopeMeters^2)-(x-rRopeMeters)^2)^(1/2))
ILine(x,dHalfRope,thetaArmatureToRope)=((dPointFromNearAxis(x,dHalfRope, thetaArmatureToRope))^2)*IMultiplier(x)
ISlice(dHalfRope,thetaArmatureToRope)=definite_integral(ILine(x,dHalfRope,thetaArmatureToRope),x,0,2*rRopeMeters)
ISlice(3,4)Benji_ZhangTue, 31 Oct 2017 17:17:36 +0100https://ask.sagemath.org/question/39354/Trouble with an integralhttps://ask.sagemath.org/question/37395/trouble-with-an-integral/Hi,
Let f be the following function:
f(t, z0, z1) = (z0*z1 - 1)*(z0 - z1)/((t*z0 - 1)*(t*z1 - 1)*(t - z0)*(t - z1)*z0)
f is a nice holomorphic function and I would like to compute the contour integral
\int_{|z1|=1} \int_{|z0|=1} f(t, z0, z1) dz0/z0 dz1/z1
Assuming 0 < t < 1, the result should be -4 pi^2/(t^2-1).
In Sage:
**var("z0, z1, theta0, theta1")**
**assume(0 < t < 1)**
**f = (z0*z1 - 1)*(z0 - z1)/((t*z0 - 1)*(t*z1 - 1)*(t - z0)*(t - z1)*z0)**
**g = f.subs({z0: exp(I*theta0), z1: exp(I*theta1)})**
Now if I integrate with respect to theta0 first: **g.integrate(theta0, 0, 2*pi)** Sage answers that the integral is zero.
If I integrate with respect to theta1 first: **factor(g.integrate(theta1, 0, 2*pi).integrate(theta0, 0, 2*pi))** Sage answers that the integral is -4*pi^2/t^2 which is also clearly wrong...
Maple finds the right answer.
What can I do to make Sage compute it right? (This is a test I need to compute much more complicated integrals after this so I have to make sure Sage gives me the right answer).
RoroMon, 24 Apr 2017 17:21:44 +0200https://ask.sagemath.org/question/37395/Integrate piecewise function with change of variablehttps://ask.sagemath.org/question/37114/integrate-piecewise-function-with-change-of-variable/I would like to integrate a piecewise defined function while operating a change of variable. I start by defining the function and another variable involved in the change of variable:
phi(x) = piecewise([([-1,1], (1-abs(x))*(1-abs(x))*(1+2*abs(x)))]);
phi(x) = phi.extension(0);
h=pi/n;
h=h.n();
What I would like to do is integrate the function `phi(x/h-1)` between `0` and `pi` so I try it and results in
integral(phi(x/h-1),x,0,pi)
ValueError: substituting the piecewise variable must result in real number
So I then try to use another variable which I try to define to be 'real'
t=var('t')
assume(t,'real');
integral(phi(t/h-1),t,0,pi)
but it results in the same error... Now I try the "lambda" method since it worked when calling the `plot` function with the same change of variable; but fail again
integral(lambda t: phi(t/h-1),t,0,pi)
TypeError: unable to convert <function <lambda> at 0x16d71f140> to a symbolic expression
Now I try to use another integration method with `definite_integral` but get the same errors, only different for the "lambda" method
definite_integral(lambda x: phi(x/h-1),x,0,pi)
TypeError: cannot coerce arguments: no canonical coercion from <type 'function'> to Symbolic Ring
Is there any way around this? I really do not know what else to try...
jrojasquWed, 29 Mar 2017 01:28:56 +0200https://ask.sagemath.org/question/37114/Sage Interactive has Attribute errorhttps://ask.sagemath.org/question/30132/sage-interactive-has-attribute-error/ Herr is my code for a double integrator interactive I am making that both make a double integral and shows a graph with added rectangles. However in my code I get an attribute error I don't know.
from sage.plot.plot3d.shapes import Box
x,y = var('x,y')
html("<h1>triple integrater<h1>")
permutations = ["dx dy","dy dx"]
@interact
def interplay(order= permutations,function= input_box(sin(x*y)),lower_x_bound= input_box(0.1.1),upper_x_bound = input_box(1),lower_y_bound=input_box(0),upper_y_bound=input_box(1),showGraph = checkbox(default = False), numrecs= input_box(50)):
if permutations == "dx dy":
result = integral(integral(function,x,lower_x_bound,upper_x_bound),y,lower_y_bound,upper_y_bound)+function(lower_x_bound,lower_y_bound)+function(lower_x_bound,lower_y_bound)#function.integrate(x,lower_x_bound,upper_x_bound).integrate(y,lower_y_bound,upper_y_bound)
q="$\int_%s^{%s} \int_%s^%s %s $" % (lower_y_bound, upper_y_bound,lower_x_bound,upper_x_bound,function)
# puts expressions inside latex
else:
result =integral(integral(function,y,lower_y_bound,upper_y_bound),y,lower_x_bound,upper_x_bound)
#actually calculates integral
q="$\int_%s^{%s} \int_%s^%s %s $" % (lower_x_bound,upper_x_bound,lower_y_bound,upper_y_bound,function)
#if type(lower_x_bound)!=float or type(upper_x_bound)!=float or type(lower_y_bound)!= float or type(upper_y_bound)!= float :
if lower_x_bound in RR or upper_x_bound in RR or lower_y_bound in RR or lower_y_bound in RR:
#check if bounds are are real before graphing because I do nto know how to graph with x as a bound.
showGraph = True
html("Can only grah numerical bounds")
else:
showGraph = False
if showGraph == True :
graph = plot3d(function,(x,lower_x_bound,upper_x_bound),(y,lower_y_bound,upper_y_bound),fill=True,color = "orange",spin = 4)
html("<h3>Graph of Integrated Region</h3>")
delta = upper_x_bound - lower_x_bound
B = sum([Box([1/numrecs,.5,abs(function(lower_x_bound+(i-1)*delta/numrecs , .2))], color="orange").translate((lower_x_bound+delta*i/numrecs,0,function(lower_x_bound+i*delta/numrecs)/2)) for i in [0..numrecs]])
#makes a whole bunch of rectangels which approximate graph of function being integrated
show(graph+B)
html("<h3>Numerical Result</h3>")
#s = "$\int_{2}^{3} \int_{4}^{5} {0} \,dxdy = {1} $"
#p = s.format(function, result,lower_x_bound,upper_x_bound,lower_y_bound,upper_y_bound)
html("%s" %q)
#shows the result
I am getting this error. I do not know what it means.
Error in lines 5-29
Traceback (most recent call last):
File "/projects/454b81d2-ef23-4b95-bd57-5c718a468ea1/.sagemathcloud/sage_server.py", line 881, in execute
exec compile(block+'\n', '', 'single') in namespace, locals
File "", line 2, in <module>
File "sage/structure/element.pyx", line 418, in sage.structure.element.Element.__getattr__ (/projects/sage/sage-6.9/src/build/cythonized/sage/structure/element.c:4670)
return getattr_from_other_class(self, P._abstract_element_class, name)
File "sage/structure/misc.pyx", line 259, in sage.structure.misc.getattr_from_other_class (/projects/sage/sage-6.9/src/build/cythonized/sage/structure/misc.c:1771)
raise dummy_attribute_error
AttributeError: 'sage.rings.real_mpfr.RealLiteral' object has no attribute 'gen'collabmathTue, 20 Oct 2015 08:35:13 +0200https://ask.sagemath.org/question/30132/Is this a known bug with integral()https://ask.sagemath.org/question/30075/is-this-a-known-bug-with-integral/I've tried to compute the following integral wth integral() in a SageMathCloud worksheet: $\displaystyle \int_{-\pi/6}^{\pi/6}\frac{\cos x}{1+\sin x}dx$.
The output was an error message (saying the integral is divergent), just like the one I got in SageMathCell (see link):
https://sagecell.sagemath.org/?z=eJzzVLBVyMwrSU0vSszRSM4v1qjQ1Ncw1C7OzAOyNHUUKnQUdAsy9c10FECkJi9XcUZ-uYanJgDa5Q_i&lang=sage
So I tried with integrate() and with numerical_integral() as well. I was never able to obtain the value of this integral, which turns out to be $\ln(3)$ after an obvious substitution.
Is this a bug?
Note that replacing 1 by 1.1 yields this:
https://sagecell.sagemath.org/?z=eJzzVLBVyMwrSU0vSszRSM4v1qjQ1Ncw1DPULs7MA7I1dRQqdBR0CzL1zXQUQKQmL1dxRn65hqcmAPXGEEE=&lang=sage
while we get that when replacing 1 by 2:
https://sagecell.sagemath.org/?z=eJzzVLBVyMwrSU0vSszRSM4v1qjQ1Ncw0i7OzAOyNHUUKnQUdAsy9c10FECkJi9XcUZ-uYanJgDbCA_j&lang=sageJulienSat, 17 Oct 2015 17:01:02 +0200https://ask.sagemath.org/question/30075/Simplify result of this definite integralhttps://ask.sagemath.org/question/10503/simplify-result-of-this-definite-integral/It is well known that for $n\in\mathbb{N}$ and $n>0$ (an maybe even for more than these restrictions): $$I_n = \int_0^\infty\frac{x^n}{e^x-1}dx = \zeta(n+1)n!$$ which, analytically can be shown easily by expanding $1/(1-e^{-x})$ into a geometric series, which leads to trivial integrals, and by using $\zeta(n+1)=\sum_{l=1}^\infty l^{-(n+1)}$. So, eg.: $$I_1 = \pi^2/6$$ $$I_2 = 2\zeta(3)$$ a.s.o...
Now, if I try even the simplest case with sage, I get this 'nifty' little results
sage: integrate(x/(exp(x)-1),x,0,oo)
-1/6*pi^2 + limit(-1/2*x^2 + x*log(-e^x + 1) + polylog(2, e^x), x,
+Infinity, minus)
**Is there any trick to simplify this** down to the final result, or is this about as far as I can get with sage alone?
PS.: it is probably needless to say that (once again ... :( ...)
In[1]:= Integrate[x/(Exp[x] - 1), {x, 0, Infinity}]
Out[1]:= Pi^2/6
MarkWed, 04 Sep 2013 17:06:49 +0200https://ask.sagemath.org/question/10503/Solving this DE containing an integralhttps://ask.sagemath.org/question/28643/solving-this-de-containing-an-integral/I am trying to solve
$$ 0 = - \partial_a F(a)-e(a)F(a) + \int_0^{a} e(a')\partial_a F(a') d a' + n $$
optimally, without specifying e(a). But if necessary (as I guess), e(a) = k1*exp(k2*a). Here's my code:
var('a b k_1 k_2 n')
e(b) = k_1*exp(b*k_2)
F = function('F', a)
g(b) = e(b)*diff(F,b,1)
de = -diff(F, a, 1) - e(a)*F(a) + g(b).integral(b, 0, a) + n
y = desolve(de, F, ivar=a); y
And the output is
(_C + n*Ei(k_1*e^(a*k_2)/k_2)/k_2)*e^(-k_1*e^(a*k_2)/k_2)
However, I believe that something is wrong with my integral, it is not doing what I expect it to do. For example, if I change the integration boundary to 1:
de = -diff(F, a, 1) - e(a)*F(a) + g(b).integral(b, 0, a) + n
I will still get the same result:
(_C + n*Ei(k_1*e^(a*k_2)/k_2)/k_2)*e^(-k_1*e^(a*k_2)/k_2)
Where am I going wrong?FooBarSun, 19 Jul 2015 14:13:44 +0200https://ask.sagemath.org/question/28643/Problem with integralhttps://ask.sagemath.org/question/27235/problem-with-integral/Considering my last question ('Problem with hypergeometric') I tried to replace my Ansatz with a different formula. Here what happened:
F = lambda z: (2/pi)*integral((4*cos(x)^2-1)^z*sin(x)^2,x,0,pi)
print F(1/2)
RuntimeError: ECL says: Error executing code in Maxima:
With Maple:
F := z -> (2/Pi)*int((4*cos(x)^2-1)^z*sin(x)^2,x=0..Pi);
evalf(F(1/2)); .3697166864+.4838437554*I
Oh mei oh mei ...Peter LuschnyMon, 29 Jun 2015 14:59:58 +0200https://ask.sagemath.org/question/27235/Another problem with integralhttps://ask.sagemath.org/question/27237/another-problem-with-integral/This is a follow-up to 'Problem with integral' which is a follow-up of 'Problem with hypergeometric'. I am still trying to solve the same basic problem with Sage and I am just reporting what I am experiencing.
F = lambda z: (1/pi)*integral((x-1)^z*sqrt(1/x-1/4), x,0,4)
print F(1/2).n()
NaN
print F(3/2).n()
0.509025648974361 Exception ValueError: ValueError('negative number to a fractional power not real',) in 'sage.gsl.integration.c_ff' ignored [The error message some 20 times.]
With Maple:
F := z -> (1/Pi)*int((x-1)^z*sqrt(1/x-1/4), x=0..4);
evalf(F(1/2)); 0.3697166867 + 0.4838248688*I
evalf(F(3/2)); 0.5090256475 - 0.3669993270 IPeter LuschnyMon, 29 Jun 2015 15:21:52 +0200https://ask.sagemath.org/question/27237/integral should not be zerohttps://ask.sagemath.org/question/24532/integral-should-not-be-zero/
F = sqrt((cos(x) - 1)^2 + sin(x)^2)
F.integrate(x, 0, 2*pi)
yields 0, the expected answer is 8.
jllbMon, 20 Oct 2014 00:44:26 +0200https://ask.sagemath.org/question/24532/What does "Runtime Error: ECL says: ... is not of type FIXNUM" mean and how to fix it?https://ask.sagemath.org/question/10908/what-does-runtime-error-ecl-says-is-not-of-type-fixnum-mean-and-how-to-fix-it/I am trying to integrate $x(0.6x^{0.5}+0.6)$ from $0$ to 1.
Here's what I tried:
var('x')
(x*(0.6*x^0.5+0.6)).integrate(x,0,1)
But I received the following error:
RuntimeError: ECL says: 3.0 is not of type FIXNUM.
What does the error mean (I am especially curious where the 3 came from) and what can I do to correctly evaluate the definite integral? According to Wolfram Alpha, the answer is 0.54.ensabaMon, 13 Jan 2014 10:42:37 +0100https://ask.sagemath.org/question/10908/symbolic integrationhttps://ask.sagemath.org/question/10724/symbolic-integration/Hi,
I am a sage-noob. To calculate the vortex sheet of a flat plate in potential flow, I have to solve some integrales of such a king:
**Mathematica syntax:** Integrate[Exp[-I * t * 2 * m * k]*((1/t+1)^0.5-1),t,0, Infinity]
And this is the reult:
If[Im[k m] < 0,
((0. + 0.5 I) - (0. + 0.886227 I) HypergeometricU[-0.5, 0, (2 I) k m])/km
My approach in **Sagemath** is:
f(x) = exp(-I*x*2*m*k)*((1/x+1)^0.5-1)
integral(f, x, 0, infinity)
But Sagemath is asking for assumptions regarding m and k. Im[k m] < 0 would be the appropriate assumption. What would be the right syntax? Thank you very much for your answers.
Best wishes, Chris
chris42Mon, 11 Nov 2013 09:24:05 +0100https://ask.sagemath.org/question/10724/Fermi-Dirac integral of half orderhttps://ask.sagemath.org/question/10517/fermi-dirac-integral-of-half-order/I am trying to implement a 1D model for semiconductor pn-junctions. This involves evaluating the Fermi-Dirac integral of half order, which can only be done numerically. I saw that the GSL library has an algorithm to perform this integration, but I can't figure out how to call it in Sage, is this possible? If not, what are some alternatives to evaluate this integral? Thanks in advance.wlp2Fri, 06 Sep 2013 14:20:20 +0200https://ask.sagemath.org/question/10517/How to integrate in 2D, along the locus of a line.https://ask.sagemath.org/question/10348/how-to-integrate-in-2d-along-the-locus-of-a-line/If I have a 2D continuous and differentiable function (f(x,y)) and a general 2D line L (ax + by + c = 0), how do I evaluate the definite integral of f with respect to x and y along the line L between an arbitrary start and end point that both lie on the line?mmsood99Thu, 11 Jul 2013 19:56:46 +0200https://ask.sagemath.org/question/10348/Change of variable in an integrationhttps://ask.sagemath.org/question/8679/change-of-variable-in-an-integration/How to indicate a change of variable to Sage in an integration when Sage seems clueless?Green diodSat, 28 Jan 2012 18:59:27 +0100https://ask.sagemath.org/question/8679/