# Python: Integrating a function but getting large errors

• Python
• MathewsMD
In summary: Gaussian function. You should probably move the random.randint calls outside of the G function and call them once to define sigma, r0 and theta0 before evaluating the integral.This is what I've done, and my code now prints correctly:import numpy as npimport matplotlib.pylab as pltimport mathimport randomfrom scipy import integrateRTIT = []R1 = 4. #
MathewsMD
My code:
Python:
import numpy as np
import matplotlib.pylab as plt
import math
import random
from scipy import integrate

R1 = .001
R2 = 7

def G(r,theta):
sigma = random.randint(4000., 7000.)/1000. # width of beam is 4 - 7mm
r0 = random.randint(0, R1*1000.)/1000. #random centroid
theta0 = random.uniform(0, np.pi*2) #angle
return (100/(np.pi*2*sigma**2))*(np.e**(-((r**2 + r0**2 - 2*r*r0*(np.cos(theta)*\
np.cos(theta0) + np.sin(theta)*np.sin(theta0)))/2*sigma**2)))*r # this r is here because the integrand is dr and dtheta, NOT dx and dy any longer!
#amplitude is 100

print RTI
I keep running this code, and everything seems to be working, but I keep getting results like: (0.1406360958428128, 0.012357271987783056)

Also, the code itself takes quite a while to run and I'm sure this is an indication of something...just not sure where it's going on. As you can see, the error is almost the value of integration itself, and this error is to large. I've been looking at the code but am not sure why such a large error is arising. If anyone has any ideas, it would be greatly appreciated!

Last edited by a moderator:
I'm not sure what exactly you are trying to do. The integrate.nquad function will call the function G many times as it evaluates the integral. Each time it calls G, the parameters sigma, r0 and theta0 will have different values. So the value of the integral isn't really defined, because the function G is a different function each time it is called. I suspect that this isn't what you intend. You should probably move the random.randint calls outside of the G function and call them once to define sigma, r0 and theta0 before evaluating the integral. Does this make sense?

MathewsMD said:
Also, the code itself takes quite a while to run and I'm sure this is an indication of something...
It's an indication that the integrator is struggling.

A lousy numerical integrator might arbitrarily chop the space to be integrated into fixed size chunks, call the derivative function at each grid point, and apply some mathematical formulae to generate an estimate of the integral over than space. A better integrator will subdivide the space according to sensitivities revealed by calls to the derivative function.

Your derivative function involves random. A good integrator will detect that. What a good integrator won't do is detect that your derivative function (in the context of computer science) is not a "function" (in the context of mathematics). Any integrator must necessarily assume that the function to be integrated is indeed a function. You don't have a function. You have randomness.

As you can see, the error is almost the value of integration itself, and this error is to large.
What, exactly, are you trying to integrate?

phyzguy said:
I'm not sure what exactly you are trying to do. The integrate.nquad function will call the function G many times as it evaluates the integral. Each time it calls G, the parameters sigma, r0 and theta0 will have different values. So the value of the integral isn't really defined, because the function G is a different function each time it is called. I suspect that this isn't what you intend. You should probably move the random.randint calls outside of the G function and call them once to define sigma, r0 and theta0 before evaluating the integral. Does this make sense?

I have attached an image of what I am trying to do. Yes, you seem to get what I was attempting. I want to generate a single particular gaussian with the variables r0, theta0 and sigma0 randomly generated but held constant for that one run, then I want to integrate that one particular function over the circle. I would be creating numerous random gaussian functions like this.

I have modified the code a little bit based on your suggestions, and it seems to be working, but any input with regards to thingsto modify would be great!

Code:
Code:
RTIT = []

R1 = 4. #
R2 = 7. #

i = 0

while i < 10:

i = i + 1

sigma0 = random.randint(4000., 7000.)/1000. # width is 4 - 7mm
r0 = random.randint(0, R1*1000.)/1000. #random centroid
theta0 = random.uniform(0, np.pi*2) #angle centroid makes with polar axis

def G(r,theta): #this is the Gaussian
return (100/(np.pi*2*sigma0**2))*(np.e**(-((r**2 + r0**2 \
- 2*r*r0*(np.cos(theta)*np.cos(theta0) + \
np.sin(theta)*np.sin(theta0)))/2*sigma0**2)))*r # this r is here because
#the integrand is dr and dtheta, NOT dx and dy any longer!
#intensity is 100

RTIT.append(RTI)

print RTIT

#### Attachments

• Photo on 2015-05-21 at 10.47 AM.jpg
62.5 KB · Views: 442
Last edited by a moderator:
A couple of things:

If you enclose your code in
Code:
tags, then the code will be more readable.

Your code with the modifications looks good. Did it fix the large error problem you were initially having?

MathewsMD
phyzguy said:
A couple of things:

If you enclose your code in
Code:
tags, then the code will be more readable.

Your code with the modifications looks good. Did it fix the large error problem you were initially having?

Yep, it seems to be working great now. Thanks! I'll definitely use that from now on.

## 1. Why am I getting large errors when integrating a function in Python?

There could be a few reasons for this. First, check your code for any mistakes or typos. Make sure you are using the correct syntax and that all variables are properly defined. Also, check the accuracy and precision of your function. If your function has a large range of values, it may be helpful to break it into smaller sections and integrate each section separately. Additionally, you may need to adjust your integration method or step size to improve accuracy.

## 2. How can I improve the accuracy of my function integration in Python?

There are a few things you can try. First, make sure your function is properly defined and that you are using the correct integration method for your specific function. Adjusting the integration step size can also improve accuracy. If your function has a large range of values, try breaking it into smaller sections and integrating each section separately. You can also try using a more advanced integration method, such as the Simpson's rule or Gaussian quadrature.

## 3. What is the best integration method to use in Python?

The best integration method will vary depending on the specific function you are integrating. Some common methods include the trapezoidal rule, Simpson's rule, and Gaussian quadrature. It is important to choose a method that is suitable for your function and that can provide the desired level of accuracy. You may need to experiment with different methods and adjust the step size to find the best approach for your specific integration problem.

## 4. Can I integrate a function with multiple variables in Python?

Yes, it is possible to integrate a function with multiple variables in Python. You can use the scipy.integrate.nquad() function to integrate a function with multiple variables. This function takes in the function to be integrated and the limits for each variable, and returns the integrated value. It is important to make sure your function is properly defined and that you are using the correct syntax for the nquad() function.

## 5. Is there a limit to the number of integrals I can perform in Python?

There is no specific limit to the number of integrals you can perform in Python. However, as the number of integrals increases, the accuracy and precision may decrease. It is also important to consider the computational resources and time required to perform multiple integrals. It may be helpful to break the integrals into smaller sections and integrate each section separately to improve accuracy and efficiency.

Replies
3
Views
2K
Replies
3
Views
1K
Replies
5
Views
1K
Replies
5
Views
2K
Replies
7
Views
1K
Replies
5
Views
2K
Replies
6
Views
1K
Replies
1
Views
1K
Replies
3
Views
1K
Replies
3
Views
2K