![]() |
function handling - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: function handling (/thread-4759.html) |
function handling - JohnCrichton - Sep-06-2017 Hi All! I'm pretty new to Python coding and I'm doing some stuff while I learn the language, I have some experience with Matlab especially for mathematical computation so I'm not totally new to coding. But here is my problem: I have made a function that solves f(x) = 0 and returns x. It is a standard bysection method and it works well. What I have done so far was to define a function that I then fed to the bysection: def my_fun(x): y = x*2 + 4 return y def main() x = bysection(my_fun) print(x) return This configuration WORKS, it gives me back the correct x and produces no errors. The problem is when I want to have my_fun function of a parameter as well. def my_fun(x, b): y = x*2 + b return y The bisection function solves only f(x) = 0 and not f(x,b) = 0. What I want to do is to pass to the bysection my_fun where x is free and b is assigned: def main() b = 4 x = bysection(my_fun(x, b)) print(x) return Of course this doesn't work, do you guys have any idea? Matlab allowed me to define the function INSIDE the main, so b was already assigned, but in Python I have to define the function and then assign only b but keeping x as the only variable. Basically can I go from: function(x,b) to function(x) by assigning a value for b? Thanks in advance for your help! RE: function handling - ichabod801 - Sep-07-2017 First, give b a default: def my_fun(x, b = 1): y = x * 2 + b return yThen make a function wrapper: def set_b(my_func, b): def b_set(x): return my_func(x, b = b) return b_setThen, wrap the function: def main(): b = 4 x = bysection(set_b(my_fun, b)) print(x)Then, read the BBCode link in my signature (below) to learn how to use python tags in your own posts. RE: function handling - JohnCrichton - Sep-07-2017 That works just about right, thank you very much for your help! |