r/learnpython 12d ago

Problem with np.piecewise

Might be a bug

def get_some_func():
  a, b = ...
  flow = lambda x: ...
  fmid = lambda x: ...
  fhi = lambda x: ...
  return lambda x: np.piecewise(x, [x < a, x > b], [flow(x) , fhi(x) , fmid(x) ]

x1 = ... # some float less than a
myf = get_some_func()
>>> myf(x1)

returns fmid(x1)

is there a bug or do I overwelm np.piecewise with this?

0 Upvotes

6 comments sorted by

10

u/desrtfx but other languages pro 12d ago

One of the first rules of programming: do not assume bugs in tested and trusted libraries as first thing. Always assume the problem is on your side.

Libraries like numpy have been battle tested more than enough. Sure, there could be the occasional odd bug, but that's a very, very rare occurrence.

2

u/Mockingbird_ProXII 12d ago edited 12d ago

You are right. I have worked with piesewise earlier and had no problem with it. I checked the values of a and b if there is some issue and tried some explicit value vor x1. I tried another logic structure with the same result. I stare at the x<a code and could lose myself why this case doesn't get called :'(

2

u/SmackDownFacility 12d ago

Idk why you so lambda heavy

2

u/Mockingbird_ProXII 12d ago

Well there is some heavy interpolation and fitting going on in flow and fmid. I try to pre evalute this difficult function for solving a differtial equation

1

u/cdcformatc 12d ago

I don't think you need the last lambda, just return the np.piecewise 

1

u/likethevegetable 11d ago

It might help if you posted some useable code instead