Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
function handling
#1
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!
Reply
#2
First, give b a default:

def my_fun(x, b = 1):
    y = x * 2 + b
    return y
Then make a function wrapper:

def set_b(my_func, b):
    def b_set(x):
        return my_func(x, b = b)
    return b_set
Then, 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.
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply
#3
That works just about right, thank you very much for your help!
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
Star python exception handling handling .... with traceback mg24 3 1,289 Nov-09-2022, 07:29 PM
Last Post: Gribouillis
  TicTacToe Game Add Exception Handling and Warning Function ShaikhShaikh 5 2,433 Nov-03-2021, 05:02 PM
Last Post: deanhystad

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020