Difference between revisions of "Software tutorial/Functions as objects"
Jump to navigation
Jump to search
m (Created page with "<syntaxhighlight lang="matlab"> f = inline('1/x - (x-1)') fzero(f,1) roots(...) </syntaxhighlight>") |
m |
||
Line 1: | Line 1: | ||
From this point onward in the course we will often have to deal with an arbitrary function, such as finding the function's zeroor integrating the function between two points. It is helpful if we can write MATLAB or Python code that can operate on '''any''' function, not just a specific function, \(f(x)\). | |||
For example, if we write a Python function to find the zero of \(f(x) = 3x - \frac{2}{x}\), then we would like to send that function, let's call it <tt>my_function</tt>, into another Python function that will find the zero of that function. | |||
<syntaxhighlight lang="python"> | |||
def my_function(x): | |||
""" | |||
Returns the value of f(x) = 3x - x/2, at the given x | |||
""" | |||
return 3*x - 2/x | |||
lower = 0.1 | |||
upper = 3.0 | |||
root = bisection_method(my_function, lower, upper) | |||
</syntaxhighlight> | |||
<syntaxhighlight lang="matlab"> | <syntaxhighlight lang="matlab"> | ||
f = inline('1/x - (x-1)') | f = inline('1/x - (x-1)') |
Revision as of 22:01, 17 October 2010
From this point onward in the course we will often have to deal with an arbitrary function, such as finding the function's zeroor integrating the function between two points. It is helpful if we can write MATLAB or Python code that can operate on any function, not just a specific function, \(f(x)\).
For example, if we write a Python function to find the zero of \(f(x) = 3x - \frac{2}{x}\), then we would like to send that function, let's call it my_function, into another Python function that will find the zero of that function.
def my_function(x):
"""
Returns the value of f(x) = 3x - x/2, at the given x
"""
return 3*x - 2/x
lower = 0.1
upper = 3.0
root = bisection_method(my_function, lower, upper)
f = inline('1/x - (x-1)')
fzero(f,1)
roots(...)