How to find maximum from given function with given range in python? - python

I have implemented functions find_maximum and f, that returns the value and passed it as a parameter to another function and just wanted to find the maximum of the given function. Following is my implementation.
import numpy as np
def find_maximum(f, begin_range, end_range, step=0.00001):
return np.maximum(begin_range, np.minimum(f, end_range))
def f(x):
myList = []
for i in range(1,4):
myList.append(0.3333* x**2) - 5*x - 3 + (numpy.cos(3)*x)
return myList
x = 4
print(find_maximum(f, -4, 4, 0.00001))
Following is more explanation
f - A vectorized python function of a single variable f(x), that expects
a numpy array of x values as its only parameter.
begin_range, end_range - real valued numbers with begin_range < end_range,
defining a range that we want to determine the maximum value of the
given function within.
step - The step size to search within the range, defaults to 0.001 The
maximum will be determined to a value within this step size, so it
represents the accuracy with which to find the maximum.
Returns max_loc - returns the location where the function is at the maximum in
the given range. The location of the maximum must be within the range:
begin_range <= max_loc <= end_range
An Error
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-6-b68bd5d55098> in <module>()
29 return myList
30 x = 4
---> 31 print(find_maximum(f, -4, 4, 0.00001))
<ipython-input-6-b68bd5d55098> in find_maximum(f, begin_range, end_range, step)
1 import numpy as np
2 def find_maximum(f, begin_range, end_range, step=0.00001):
----> 3 return np.maximum(begin_range, np.minimum(f, end_range))
4 '''Find the maximum of function f in the range [begin_range, end_range].
5 The function f should be a vectorized python function of a single
TypeError: '<=' not supported between instances of 'function' and 'int'
Expected output
print(find_maximum(f, -4, 4, 0.00001))
>>> -2.14085

Try like this :
x = 4
print(find_maximum(f(x), -4, 4, 0.00001))
You need to run your function before give it to find_maximum
Edit :
You function miss a parenthesis :
def f(x):
myList = []
for i in range(1,4):
myList.append((0.3333* x**2) - 5*x - 3 + (np.cos(3)*x))
return myList

Related

Conver a loop from Pinescript to Python

Im tryng to convert this formula (WMA Moving Average) for loop in Python from Pinescript
but for i to x not exist. I tried for i in range(x) but seems dont return same result.
What exactly means to? Documentation of Pinescript said means from i to x but i dont find the equivalent in Python
pine_wma(x, y) =>
norm = 0.0
sum = 0.0
for i = 0 to y - 1
weight = (y - i) * y
norm := norm + weight
sum := sum + x[i] * weight
sum / norm
plot(pine_wma(close, 15))
Python Code:
import pandas as pd
dataframe = pd.read_csv('dataframe.csv')
def formula_wma(x, y):
list = []
norm = 0.0
sum = 0.0
i = 0
for i in range(y - 1):
weight = (y - i) * y
norm = norm + weight
sum = sum + x[i] * weight
_wma = sum / norm
list.append(_wma)
i += 1
return list
wma_slow = formula_wma(dataframe['close'],45)
dataframe['wma_slow'] = pd.Series(wma_slow, index=dataframe.index[:len(wma_slow)])
print(dataframe['wma_slow'].to_string())
Output:
0 317.328133
[Skipping lines]
39 317.589010
40 317.449259
41 317.421662
42 317.378052
43 317.328133
44 NaN
45 NaN
[Skipping Lines]
2999 NaN
3000 NaN
First of all, don't reassign built-in names!
sum is a built-in function that calculates the summation of a sequence of numbers. So is list, it is a class constructor.
For example:
sum(range(10)) returns 45.
The above is equivalent to:
numbers = (0,1,2,3,4,5,6,7,8,9)
s = 0
for i in numbers: s += i
Second, don't increment the variable you use for looping inside the loop, unless you have a good reason for it.
That i += 1 at the end of the loop has no effect whatsoever, for loop automatically reassigns the name to the next item in the sequence, in this case the next item is incremented by one, so i automatically gets incremented.
Further, if there is anything using i after that line, they will break.
Lastly, the reason you are not getting the same result, is Python uses zero-based indexing and range excludes the stop.
I don't know about pine script, but from what you have written, from x to y must include y.
For example 0 to 10 in pine script will give you 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
But using range(10):
print(list(range(10)))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Why? Because there are exactly ten numbers in the range you specified.
In the first example, there are actually eleven numbers. If you know your math, the number of terms in an arithmetic sequence is the difference between the maximum term and the minimum term divided by the increment plus one.
So how to solve your problem?
Remove - 1 after y in range!
Fixed code:
import pandas as pd
dataframe = pd.read_csv('dataframe.csv')
def formula_wma(x, y):
lst = []
norm = 0.0
sum_ = 0.0
i = 0
for i in range(y):
weight = (y - i) * y
norm = norm + weight
sum_ = sum_ + x[i] * weight
_wma = sum_ / norm
lst.append(_wma)
return lst
wma_slow = formula_wma(dataframe['close'],45)
dataframe['wma_slow'] = pd.Series(wma_slow, index=dataframe.index[:len(wma_slow)])
print(dataframe['wma_slow'].to_string())

Compute Riemann sums for double integral over regions in Python (TypeError)

I want to compute the Riemann sums of the double integral
double integral
f = lambda y,x: x*y/(x**2 + y**2)
partition = 50
x = np.linspace(0.00001, 1, 200)
y = np.linspace(1-x, 1, 200)
def Riemann(function, x_low, x_up, y_low, y_up, x_part, y_part):
dx = (x_up - x_low)/x_part
dy = (y_up - y_low)/y_part
dA = dx*dy
sum = 0
x_or = dx/2
y_or = dy/2
for m in range (0,x_part-1):
for n in range (0,y_part-1):
y_or += n*dy
x_or += m*dx
sum += function(y_or,x_or)*dA
return sum
print(Riemann(f,0,1,lambda x:1-x,1,partition,partition))
But it returns this error:
TypeError Traceback (most recent call last)
<ipython-input-10-fdd53b3a35ef> in <module>()
17 return sum
18
---> 19 print(Riemann(f,0,1,lambda x:1-x,1,partition,partition))
<ipython-input-10-fdd53b3a35ef> in Riemann(function, x_low, x_up, y_low, y_up, x_part, y_part)
4
5 dx = (x_up - x_low)/x_part
----> 6 dy = (y_up - y_low)/y_part
7 dA = dx*dy
8 sum = 0
TypeError: unsupported operand type(s) for -: 'int' and 'function'
I really don't know how to solve this... But if i write
print(Riemann(function,0,1,1,0,x_part,y_part))
then it will return 0.34467033928271357, while the correct answer is 0.20387450858124856
You are passing in a function to a variable and then treating it as an integer.
print(Riemann(f,0,1,lambda x:1-x,1,partition,partition))
The code:
lambda x:1-x
will be treated as a function. If you want to pass in 1-x then call the function with:
print(Riemann(f,0,1,1-x,1,partition,partition))
This will fix your current error but I am not entirely sure what it is you are trying to acheive.
You are sending a function (instead of a float or integer) as parameter y_low to your function def Riemann():
type(lambda x: 1-x)
function
Use the correct format and it should be solved

How to compute the following equation correctly?

Using python 2.7 I am trying to compute the following rather difficult set of equations.
I have successfully implemented the first two, but am struggling with the third. Here is my attempt,
def pi_tau( r ):
return (1 - (1 - r)**(t + 1))/(2 - r)
def mean_field( r ):
return 1 - (1 - r)**t
def pi_neighbour( r ):
inside = []
for kappa_dash in range(0, kappa - 1):
Binomial_Coefficient = (math.factorial(kappa - 1)) / (math.factorial(kappa - 1 - kappa_dash)*math.factorial(kappa_dash))
top = ((mean_field( r )*pi_tau( r ))**kappa_dash)*(1 - mean_field( r )*pi_tau( r ))**(kappa - 1 - kappa_dash)
bottom = kappa_dash + 1
fraction = top/bottom
inside.append(kappa_dash)
inside[kappa_dash] = inside[kappa_dash] + fraction*Binomial_Coefficient
return pi_tau*inside
I then try to call this function
# set parameters
r = 0.15
kappa = 2.1
T = 10
ppp_t = []
mmm_f = []
nnn_t = []
for t in range(0, T):
ppp_t.append(pi_tau( r ))
mmm_f.append(mean_field( r ))
nnn_t.append(pi_neighbour( r ))
I get the following error message
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-41-9bcf462306f0> in <module>()
6 ppp_t.append(pi_tau( r ))
7 mmm_f.append(mean_field( r ))
----> 8 nnn_t.append(pi_neighbour( r ))
<ipython-input-39-d9acdd7490f9> in pi_neighbour(r)
19 inside[kappa_dash] = inside[kappa_dash] + fraction*Binomial_Coefficient
20
---> 21 return pi_tau*inside
TypeError: can't multiply sequence by non-int of type 'function'
I am looking for any advice on how to implement the third function and improve on my method.
There are several weird things here:
you calculate the top, bottom, and bionomial all in the for loop, but don't sum up in that for loop; and
you multiply the pi_tau function with a list?
return pi_tau*inside
you use range(0, kappa - 1), but the upperbound of range(..) is exclusive
Nevertheless, you make things quite hard. You could use the following approach:
from math import factorial
def pi_neighbour(r):
sum = 0.0
for kappa_dash in range(0,kappa):
bin_coeff = factorial(kappa-1)/(factorial(kappa-1-kappa_dash)*factorial(kappa_dash))
top = ((mean_field(r)*pi_tau(r))**kappa_dash)*(1-mean_field(r)*pi_tau(r))**(kappa-1-kappa_dash)
sum += bin_coeff*top/(kappa_dask+1)
return pi_tau(r)*sum
What I believe you meant to do is the following in line 21 of the traceback:
return pi_tau(r)*inside
You forgot to call the function, and so it is attempting to multiply an integer by a function, rather than the return value of the function.
The error is that you are multiplying a list, that is inside and a integer, that is return of pi_tau(r)
Do this instead (a list comprehension)
try this:
return [i*pi_tau(r) for i in inside]

Python/Theano: Is it possible to construct truly recursive theano functions?

For example, I can define a recursive Python lambda function for computing the Fibonacci sequence as follows:
fn = lambda z: fn(z-1)+fn(z-2) if z > 1 else z
However, if I try to turn this into a Theano function, Theano won't accept fn because fn invokes the Boolean operation ">". So this code crashes:
z = T.scalar('z')
fn = lambda z: fn(z-1)+fn(z-2) if z > 1 else z
fibby = theano.function([z], fn(z))
But if I replace the Boolean operator with theano.tensor.gt(z,1), the code goes into an infinite recursion, so theano.tensor.gt(z,1) isn't serving the role of ">":
z = T.scalar('z')
fn = lambda z: fn(z-1)+fn(z-2) if theano.tensor.gt(z,1) else z
lappy = theano.function([z], fn(z))
print(lappy(4))
Running this results in "maximum recursion depth exceeded". What's wrong? I get the same "maximum recursion depth exceeded" error if I replace the definition of fn with
fn = lambda z: theano.ifelse(theano.tensor.gt(z,1),fn(z-1)+fn(z-2),z)
PS I am NOT looking to do this using theano.scan... because I want to learn to do this calculation recursively without resorting to an explicit loop.
--Ken
In Theano you can make a recursion using outputs_info parameter of theano.scan(fn=myfunc(), outputs_info=...) and passing previous outputs of myfunc() as arguments in the next iteration of myfunc().
In case of Fibonacci sequence the code may look like this:
import numpy as np
import theano
import theano.tensor as T
# placeholder for the number of elements in the Fibonacci sequence
t_N = T.iscalar('N')
# first two elements for Fibonacci sequence
initial = np.array([1,1], dtype=np.int32)
t_initial = theano.shared(initial)
def fibonacci_iter(prev1_value, prev2_value):
return prev1_value + prev2_value
# Iterate N-2 times over fibonacci() function
# ('taps': [-2,-1] means take two previous values in the sequence of outputs):
outputs, updates = theano.scan(
fn=fibonacci_iter,
outputs_info = [{'initial': t_initial, 'taps': [-2,-1]}], # a list of dicts or a dict
n_steps=t_N-2)
# compiled function:
fibonacci = theano.function(
inputs=[t_N],
outputs=outputs)
n = 10
fibonacci_seq = fibonacci(n)
print(np.concatenate([initial, fibonacci_seq]))
Output:
[ 1 1 2 3 5 8 13 21 34 55]
Reference:
http://deeplearning.net/software/theano/library/scan.html#theano.scan

TypeError: zip argument #1 must support iteration (Vector sum for Ipython)

Hi I'm following "Data Science from Scratch" and I got an error when I was making vector sum function. Could someone help?
The code:
a = [1,2,3]
b = [2,3,4]
def vector_add(v, w):
"""adds two vectors componentwise"""
return [v_i + w_i for v_i, w_i in zip(v,w)]
vector_add(a,b) #prints [3, 5, 7]
def vector_sum(vectors):
result = vectors[0]
for vector in vectors[1:]:
result = vector_add(result, vector)
return result
vector_sum(a)
Error:
TypeError Traceback (most recent call last)
<ipython-input-41-401c63999247> in <module>()
4 result = vector_add(result, vector)
5 return result
----> 6 vector_sum(a)
<ipython-input-41-401c63999247> in vector_sum(vectors)
2 result = vectors[0]
3 for vector in vectors[1:]:
----> 4 result = vector_add(result, vector)
5 return result
6 vector_sum(a)
<ipython-input-15-502c43cd9568> in vector_add(v, w)
4 def vector_add(v, w):
5 """adds two vectors componentwise"""
----> 6 return [v_i + w_i for v_i, w_i in zip(v,w)]
7 vector_add(a,b)
TypeError: zip argument #1 must support iteration
If you do vector_sum(a) the local variable result will be the integer "1" in your first step which is not iterable. So I guess you simply should call your function vector_sum like
vector_sum([a,b,a])
to sum up multiple vectors. Latter gives [4,7,10] on my machine.
If you want to sum up the components of one vector you should not use your vector_add function.

Categories

Resources