2

I would like to use the integral command in scipy and have a function that gets multiplied by each element in the array once.

import math 
import matplotlib.pyplot as plt
import numpy as np
import scipy.integrate as integrate
from scipy.integrate import quad, romberg
import scipy.special as special
from numpy import sqrt

yes = np.array([0,1])

def integrate(x,yes):
    return x+yes

result = quad(integrate,0,1,args=(yes))

print(result)

when I do this I get the error only size-1 arrays can be converted to Python scalars

But if I do this

import math 
import matplotlib.pyplot as plt
import numpy as np
import scipy.integrate as integrate
from scipy.integrate import quad, romberg
import scipy.special as special
from numpy import sqrt

yes = np.array([0])

def integrate(x,yes):
    return x+yes

result = quad(integrate,0,1,args=(yes))

print(result)

it gives me this (0.5, 5.551115123125783e-15) Which is exactly what I want, but I would like it for each element in the array.

Is there a way to write a for loop? I've also heard of scipy.integrate.quad_vec, but that was not working. Thank you in advance

2
  • args is supposed to get a tuple. (yes) is not a tuple, it is just yes. args=(yes,) is the correct way of passing variable yes to your function. That said, quad can only integrate one value; your function needs to return a scalar. Commented Feb 2, 2020 at 21:03
  • How do i get my function to return a scalar? Commented Feb 2, 2020 at 21:57

1 Answer 1

2

You can use quadpy, it's fully vectorized. Just make sure that your function f, if given an input x of a particular length/shape, returns an object of shape range_shape + x.shape. The result will be of shape range_shape.

import numpy as np
from quadpy import quad


def f(x):
    return np.add.outer(np.array([0, 1]), x)


val, err = quad(f, 0, 1)
print(val)
[0.5 1.5]
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.