How to do numerical integration in python? - python

I can't install anything new I need to use the default python library and I have to integrate a function. I can get the value for any f(x) and I need to integrate from 0 to 6 for my function f(x).

In discrete form, integration is just summation, i.e.
where n is the number of samples. If we let b-a/n be dx (the 'width' of our sample) then we can write this in python as such:
def integrate(f, a, b, dx=0.1):
i = a
s = 0
while i <= b:
s += f(i)*dx
i += dx
return s
Note that we make use of higher-order functions here. Specifically, f is a function that is passed to integrate. a, b are our bounds and dx is 1/10 by default. This allows us to apply our new integration function to any function we wish, like so:
# the linear function, y = x
def linear(x):
return x
integrate(linear, 1, 6) // output: 17.85
# or using lamdba function we can write it directly in the argument
# here is the quadratic function, y=x^2
integrate(lambda x: x**2, 0, 10) // output: 338.35

You can use quadpy (out of my zoo of packages):
import numpy
import quadpy
def f(x):
return numpy.sin(x) - x
val, err = quadpy.quad(f, 0.0, 6.0)
print(val)
-17.96017028290743

def func():
print "F(x) = 2x + 3"
x = int(raw_input('Enter an integer value for x: '))
Fx = 2 * x + 3
return Fx
print func()
using the input function in python, you can randomly enter any number you want and get the function or if hard coding this this necessary you can use a for loop and append the numbers to a list for example
def func2():
print "F(x) = 2x + 3"
x = []
for numbers in range(1,7):
x.append(numbers)
upd = 0
for i in x:
Fx = 2 * x[upd] + 3
upd +=1
print Fx
print func2()
EDIT: if you would like the numbers to start counting from 0 set the first value in range to 0 instead of 1

Related

python How to convert the input value into a mathematical function

How to convert an input value into a function!
x = int(input('Enter x value: '))
n = str(input('Enter n value: ')) #n= 2 * x ^ 2 - 2 * x + 2
def f(x,n):
return 2 * x ^ 2 - 2 * x + 2
Actually for what i understand, you don't need to input n.
x = int(input('Enter x value: '))
def f(x):
return 2*x**2 - 2*x+2
n = f(x)
Edit, after rereading others answer yes it probably wanted eval()
Just You can't write "2 * x ^ 2 - 2 * x + 2", the correct way is x**2 instead of x^2
You mean (?):
def f(x, n):
return n*x**2 - 2*x + 2
Or do you mean actually changing the operators?
The question as currently posed is mathematically impossible. You define x & n and are returning a function that you may or may not want to equate to n but its all defined entries.
Still guessing a little at the actual question, but if
y = input("Enter equation to evaluate")
and you expect y to be a quadratic, i.e.:
y = "a*x**b - c*x + d"
then you can get all them from:
import re
y1 = re.split('[* ]',y)
a = y1[0]
b = y1[3] #as there is a null ent between the ** we skip y1[2] and y[1] is 'x'
c = y1[5]
d = y1[8]
If you wanted the operators, then it gets a little harder to follow. So we'll cross that bridge if you do need them.
Or, as the others suggest, just use eval()!!
You could try to use eval.
x=int(input('...'))
n=input('...') # note that input returns a string
def f(x):
global n
return(eval(n))
I think,you are asking .
How to convert an input value into a mathmetical expression ?
If it is so !
use eval()
in python

More information on output array with equation and indicies

I have a math function whose output is defined by two variables, x and y.
The function is e^(x^3 + y^2).
I want to calculate every possible integer combination between 1 and some defined integer for x and y, and place them in an array so that each output is aligned with the cooresponding x value and y value index. So something like:
given:
x = 3
y = 5
output would be an array like this:
f(1,1) f(1,2) f(1,3)
f(2,1) f(2,2) f(2,3)
f(3,1) f(3,2) f(3,3)
f(4,1) f(4,2) f(4,3)
f(5,1) f(5,2) f(5,3)
I feel like this is an easy problem to tackle but I have limited knowledge. The code that follows is the best description.
import math
import numpy as np
equation = math.exp(x**3 + y**2)
#start at 1, not zero
i = 1
j = 1
#i want an array output
output = []
#function
def shape_f (i,j):
shape = []
output.append(shape)
while i < x + 1:
while j < y +1:
return math.exp(i**3 + j**2)
#increase counter
i = i +1
j = j +1
print output
I've gotten a blank array recently but I have also gotten one value (int instead of an array)
I am not sure if you have an indentation error, but it looks like you never do anything with the output of the function shape_f. You should define your equation as a function, rather than expression assignment. Then you can make a function that populates a list of lists as you describes.
import math
def equation(x, y):
return math.exp(x**3 + y**2)
def make_matrix(x_max, y_max, x_min=1, y_min=1):
out = []
for i in range(x_min, x_max+1):
row = []
for j in range(y_min, y_max+1):
row.append(equation(i, j))
out.append(row)
return out
matrix = make_matrix(3, 3)
matrix
# returns:
[[7.38905609893065, 148.4131591025766, 22026.465794806718],
[8103.083927575384, 162754.79141900392, 24154952.7535753],
[1446257064291.475, 29048849665247.426, 4311231547115195.0]]
We can do this very simply with numpy.
First, we use np.arange to generate a range of values from 0 (to simplify indexing) to a maximum value for both x and y. We can perform exponentiation, in a vectorised manner, to get the values of x^3 and y^2.
Next, we can apply np.add on the outer product of x^3 and y^3 to get every possible combination thereof. The final step is taking the natural exponential of the result:
x_max = 3
y_max = 5
x = np.arange(x_max + 1) ** 3
y = np.arange(y_max + 1) ** 2
result = np.e ** np.add.outer(x, y)
print(result[2, 3]) # e^(2 ** 3 + 3 ** 2)
Output:
24154952.753575277
A trivial solution would be to use the broadcasting feature of numpy with the exp function:
x = 3
y = 5
i = np.arange(y).reshape(-1, 1) + 1
j = np.arange(x).reshape(1, -1) + 1
result = np.exp(j**3 + y**2)
The reshape operations make i into a column with y elements and j into a row with x elements. Exponentiation does not change those shapes. Broadcasting happens when you add the two arrays together. The unit dimensions in one array get expanded to the corresponding dimension in the other. The result is a y-by-x matrix.

Linear Regression in Python

I am a brand new to programming and am taking a course in Python. I was asked to do linear regression on a data set that my professor gave out. Below is the program I have written (it doesn't work).
from math import *
f=open("data_setshort.csv", "r")
data = f.readlines()
f.close()
xvalues=[]; yvalues=[]
for line in data:
x,y=line.strip().split(",")
x=float(x.strip())
y=float(y.strip())
xvalues.append(x)
yvalues.append(y)
def regression(x,y):
n = len(x)
X = sum(x)
Y = sum(y)
for i in x:
A = sum(i**2)
return A
for i in x:
for j in y:
C = sum(x*y)
return C
return C
D = (X**2)-nA
m = (XY - nC)/D
b = (CX - AY)/D
return m,b
print "xvalues:", xvalues
print "yvalues:", yvalues
regression(xvalues,yvalues)
I am getting an error that says: line 23, in regression, A = sum (I**2). TypeError: 'float' object is not iterable.
I need to eventually create a plot for this data set (which I know how to do) and for the line defined by the regression. But for now I am trying to do linear regression in Python.
You can't sum over a single float, but you can sum over lists. E. g. you probably mean A = sum([xi**2 for xi in x]) to calculate Sum of each element in x to the power of 2. You also have various return statements in your code that don't really make any sense and can probably be removed completely, e. g. return C after the loop. Additionally, multiplication of two variables a and b can only be done by using a*b in python. Simply writing ab is not possible and will instead be regarded as a single variable with name "ab".
The corrected code could look like this:
def regression(x,y):
n = len(x)
X = sum(x)
Y = sum(y)
A = sum([xi**2 for xi in x])
C = sum([xi*yi for xi, yi in zip(x,y)])
D = X**2 - n*A
m = (X*Y - n*C) / float(D)
b = (C*X - A*Y) / float(D)
return (m, b)
You should probably put in something like A += i**2
As you must understand from the error message that you cannot iterate over a float, which means if i=2 you can't iterate over it as it is not a list, but if as you need to sum all the squares of x, you are iterating over x in for i in x and then you add the squares of i i**2 to A A+=i**2 adn then you return A.
Hope this helps!

Adding two given floating point numbers in Python?

How would I create a method with Python to add floating point numbers that are in a list, without using libraries?. The teacher gave us this code, and I didn't understand it, could anyone else give me another example?
def msum(iterable):
"Full precision summation using multiple floats for intermediate values"
partials = [] # sorted, non-overlapping partial sums
for x in iterable:
i = 0
for y in partials:
if abs(x) < abs(y):
x, y = y, x
hi = x + y
lo = y - (hi - x)
if lo:
partials[i] = lo
i += 1
x = hi
partials[i:] = [x]
return sum(partials, 0.0)
A version of the Kahan algorithm in python would look like this:
def msum(input):
sum = 0.0
c = 0.0
for x in input:
y = x - c
t = sum + y
c = (t - sum) - y
sum = t
return sum
And what does "without using other libraries" even mean? Of course you could just have
def msum(input):
return sum(input)

What is a subtraction function that is similar to sum() for subtracting items in list?

I am trying to create a calculator, but I am having trouble writing a function that will subtract numbers from a list.
For example:
class Calculator(object):
def __init__(self, args):
self.args = args
def subtract_numbers(self, *args):
return ***here is where I need the subtraction function to be****
For addition, I can simply use return sum(args) to calculate the total but I am unsure of what I can do for subtractions.
from functools import reduce # omit on Python 2
import operator
a = [1,2,3,4]
xsum = reduce(operator.__add__, a) # or operator.add
xdif = reduce(operator.__sub__, a) # or operator.sub
print(xsum, xdif)
## 10 -8
reduce(operator.xxx, list) basically "inserts" the operator in-between list elements.
It depends exactly what you mean. You could simply subtract the sum of the rest of the numbers from the first one, like this:
def diffr(items):
return items[0] - sum(items[1:])
It's tough to tell because in subtraction it's dependent on the order in which you subtract; however if you subtract from left to right, as in the standard order of operations:
x0 - x1 - x2 - x3 - ... - xn = x0 - (x1 + x2 + x3 + ... + xn)
which is the same interpretation as the code snippet defining diffr() above.
It seems like maybe in the context of your calculator, x0 might be your running total, while the args parameter might represent the numbers x1 through xn. In that case you'd simply subtract sum(args) from your running total. Maybe I'm reading too much into your code... I think you get it, huh?
Subtract function is same as sum having negative signs like this
x = 1
y = 2
sum([x, y])
>>> 3
sum([x, -y])
>>> -1
for more numbers
a = 5
b = 10
c = 15
sum([a, b, c])
sum([a, -b, -c])
In general,
Subtract function is formed by changing you list signs like this
l = [1, 2, 3, 4, ...., n]
new_l = l[0] + [-x for x in l[1:]
# Or
new_l = [-x for x in l]
new_l[0] = -newl[0]
# Or one liner,
new_l = [-x for x in l if x != l[0]]

Categories