Ask Your Question
0

how to use monte_carlo_integral ? [closed]

asked 2025-10-04 19:40:37 +0200

ortollj gravatar image

I can't use the monte_carlo_integral function, what am I doing wrong?

var('u,v')
r_uvN(u,v)=sqrt(abs(-(cos(u) + 2)*cos(v)^2*sin(u) - (cos(u) + 2)*sin(u)*sin(v)^2)^2 + 
           abs((cos(u) + 2)*cos(u)*cos(v))^2 + abs((cos(u) + 2)*cos(u)*sin(v))^2)
sS=integral(integral( r_uvN,(u,0,2*pi)),(v,0,2*pi) )
print('s symbolic : ',sS,' num : ',sS.n(20) )

f(u, v)= u * v
res=monte_carlo_integral(f, [0,0], [2,2], 10000)  # abs tol 0.1
print(' with f  :',res)

sNL=monte_carlo_integral(r_uvN, [0,2*pi], [0,2*pi], 10000)
print('with r_uvN numerical ?? : ',sNL)
edit retag flag offensive reopen merge delete

Closed for the following reason not a real question by ortollj
close date 2025-10-05 15:40:59.683840

1 Answer

Sort by » oldest newest most voted
0

answered 2025-10-04 21:08:35 +0200

ortollj gravatar image

ok I just asked the Copilot AI, Copilot gives me the answer:⚠️ Likely Cause: r_uvN is a symbolic expression, not a callable function The monte_carlo_integral function expects a Python callable—something like lambda u,v: ... or a def-defined function. But r_uvN(u, v) is a symbolic expression, and Sage doesn’t automatically convert it into a callable for GSL-based numerical integration.

That’s why your result is near-zero: the integrator is likely sampling r_uvN as a constant or failing silently to evaluate it properly. try this:

f_uv = lambda u, v: r_uvN(u, v).n()
sNL = monte_carlo_integral(f_uv, [0, 0], [2*pi, 2*pi], 10000)

and it gives :(79.04914441964019, 0.27982586027289974) which is ok

edit flag offensive delete link more

Comments

no Copilot was wrong ! it is only because limits was not good !.it is not (r_uvN, [0,2pi], [0,2pi], 10000) but

sNL=monte_carlo_integral(r_uvN, [0,0], [2*pi,2*pi], 10000)
print('with r_uvN numerical ?? : ',sNL)
ortollj gravatar imageortollj ( 2025-10-05 07:37:54 +0200 )edit

but there still a problem, but this time with symbolic integral :try the 2 values : fy=1,fz=1 ,fy=12/10,fz=13/10 on sageCell (infinite loop if fy=12/10,fz=13/10: https://sagecell.sagemath.org/?q=fhnelk

using Sagemath10.4, Ubuntu24.04, WSL,jupyter-notebook : 5.2.2 in Edge with Copilot, W11

ortollj gravatar imageortollj ( 2025-10-05 08:46:48 +0200 )edit

maybe I should open a new post with this specific problem for symbolic integral ?

ortollj gravatar imageortollj ( 2025-10-05 10:01:31 +0200 )edit

no sorry there is only infinite loop on my PC. on sageCell , it returns the integral without giving a result which is normal behavior.I will close this post.

ortollj gravatar imageortollj ( 2025-10-05 15:40:11 +0200 )edit

Question Tools

1 follower

Stats

Asked: 2025-10-04 19:40:37 +0200

Seen: 70 times

Last updated: Oct 04