Some answers are starting to get there... But the points are being connected into a line on the plot. How do we just plot the points?

import matplotlib.pyplot as plt
import numpy as np

def f(x):
 if(x == 2): return 0
 else: return 1

x = np.arange(0., 5., 0.2)

y = []
for i in range(len(x)):
   y.append(f(x[i]))

print x
print y

plt.plot(x,y,c='red', ls='', ms=5, marker='.')
ax = plt.gca()
ax.set_ylim([-1, 2])

plt.show()

Answer from litepresence on Stack Overflow
🌐
NumPy
numpy.org › doc › stable › reference › generated › numpy.piecewise.html
numpy.piecewise — NumPy v2.4 Manual
Define the signum function, which is -1 for x < 0 and +1 for x >= 0. >>> x = np.linspace(-2.5, 2.5, 6) >>> np.piecewise(x, [x < 0, x >= 0], [-1, 1]) array([-1., -1., -1., 1., 1., 1.])
🌐
NumPy
numpy.org › doc › 2.1 › reference › generated › numpy.piecewise.html
numpy.piecewise — NumPy v2.1 Manual
Define the signum function, which is -1 for x < 0 and +1 for x >= 0. >>> x = np.linspace(-2.5, 2.5, 6) >>> np.piecewise(x, [x < 0, x >= 0], [-1, 1]) array([-1., -1., -1., 1., 1., 1.])
🌐
Stack Overflow
stackoverflow.com › questions › 76106840 › making-a-piecewise-function
python - Making a piecewise function - Stack Overflow
If you call pwfun(*x) instead, with the same list x, this will be the same as calling pwfun(-6, 0, 2), i.e. the same as calling your function with the individual elements of the list.
🌐
Reddit
reddit.com › r/learnpython › how to do piecewise functions in python?
r/learnpython on Reddit: How to do piecewise functions in python?
December 11, 2015 -

Hi guys,

I'm using numpy and plotly to graph piecewise functions. I previously used matlab. I need help to essentially translate matlab piecewise functions into something I can use in python. Here's what I had in matlab:

Constant1 = 5;
Constant2 = 10;

Formula1 = @(x,y) x*Constant1;
Formula2 = @(x,y) x*Constant2;

MainFormula = @(x,y) [Formula1(x,y)*(y<=5) + Formula2(x,y)*(y>5)];

So what this would essentially do is make 'MainFormula' equal to 'Formula1' for all values of y less than or equal to 5, and it would make 'MainFormula' equal to 'Formula2' for all values of y greater than 5.

I would really appreciate any help with this.

Thanks

Top answer
1 of 2
2
def pwise (x): if x < 0: result='less than' elif x==0: result = 'equal' ... #more elif followed by else return result
2 of 2
1
The direct translation would be this: constant1 = 5 constant2 = 10 formula1 = lambda x: x*constant1 formula2 = lambda x: x*constant2 main_formula = lambda x, y: formula1(x)*(y <= 5) + formula2(x)*(y > 5) Note that I am using python style conventions. All of your variable names could be used as-is, but for style reasons lowercase variable names separated by _ are usually used. Same with the spaces I added in x,y, y<=5, and y>5, they aren't required, just recommended for readability reasons. These style recommendations are found in pep8 , and can be checked automatically by a program of the same name. Further, you could do, for example lambda x, y: x*constant1, it doesn't hurt anything, but it is unnecessary and I think it makes the code less clear. However, assuming you are using numpy arrays (which you should be), it would be easier to do this: def formula(x, y, const1=5, const2=10, sep=5): x1 = x.copy() x1[y <= sep] *= const1 x1[y > sep] *= const2 return x You can then use formula in the exact same way as MainFormula. It will default to using 5 for the first constant and 10 for the second, and 5 for the value of y to use to differentiate the two, but you can change that by passing different values to the function, such as formula(x, y, sep=200), or formula(x, y, 50, 100). If you don't care about losing your original x, you can simplify this further: def formula(x, y, const1=5, const2=10, sep=5): x[y <= sep] *= const1 x[y > sep] *= const2 In this case, whatever array you pass to formula as x will be changed in-place, so nothing is returned. This will be considerably faster than any of the previous approaches when dealing with large datasets. You could even simplify this further by doing the y calculation in the function call if you wanted: def formula(x, isy, const1=5, const2=10): x[isy] *= const1 x[~isy] *= const2 And then call it like this: formula(x, y<=5) The final approach you could do is to handle x separately: def formula(isy, const1=5, const2=10): return isy*const1 + ~isy*const2 or: lambda isy: isy*constant1 + ~isy*constant2 And then call it like this: x1 = x*isy(y <=5)
🌐
w3resource
w3resource.com › numpy › functional-programming › piecewise.php
NumPy Functional programming: piecewise() function - w3resource
Define the sigma function, which is -1 for x < 0 and +1 for x >= 0. >>> import numpy as np >>> x = np.linspace(-3.5, 3.5, 5) >>> np.piecewise(x, [x < 0, x >= 0], [-1, 1])
🌐
Medium
medium.com › @mathcube7 › piecewise-functions-in-pythons-sympy-83f857948d3
Piecewise Functions in Python’s sympy | by Mathcube | Medium
January 2, 2023 - sympy offers an easy and intuitive way to work with functions like that: the Piecewise class. For each case in the piecewise function, we define a pair (2-tuple) with the function on the subdomain (e.g. 3−𝑥²) and a condition specifying the subdomain (e.g.
🌐
GitHub
gist.github.com › addisoneee › 5878325
Piecewise Function in Python · GitHub
Piecewise Function in Python · This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters ·
Find elsewhere
🌐
Medium
medium.com › @amit25173 › understanding-numpy-piecewise-with-examples-53b4fc9b8dcf
Understanding numpy.piecewise with Examples | by Amit Yadav | Medium
February 8, 2025 - You’ve probably written if-elif-else conditions in Python before, right? Something like this: def custom_function(x): if x < 3: return x**2 else: return 3*x + 1 · Now, imagine you have a NumPy array and need to apply different functions based on conditions. Writing a loop would be slow and ugly. That’s where numpy.piecewise ...
🌐
Datagawker
datagawker.com › home › plotting piecewise functions in python and matplotlib the elegant way
Plotting Piecewise Functions in Python and Matplotlib the Elegant Way - Data Gawker
January 8, 2024 - Piecewise functions are mathematical functions that are defined by different expressions or formulas for different intervals or domains. These functions are commonly used in various fields such as mathematics, physics, and engineering to model complex systems or phenomena.
🌐
Ideal Calculator
idealcalculator.com › home › graphing piecewise function calculator | piecewise function grapher
Graphing piecewise function calculator | Piecewise function grapher
January 11, 2025 - Visualize complex piecewise functions with ease using our Graphing Piecewise Function Calculator. | Piecewise function grapher
🌐
Physics Forums
physicsforums.com › other sciences › programming and computer science
Graphing a piecewise function (Python) • Physics Forums
May 5, 2023 - Having calculated Vt, you only need to overwrite those elements where t <= t_0 is True. That can be done easily: ... Vt[t <= t_0] = V_0 plt.plot(t,Vt) Alternatively, you can explicitly allocate your points to each range: ... t = np.concatenate( [np.linspace(0,t_0, 21), np.linspace(t_0, t_max, 101)], ) Vt = np.concatenate( [V0 * np.ones(21), V0 * np.exp(-np.linspace(0,t_max-t_0,101)/tau)] ) Thank you for your help @pasmith! That is very helpful! Python Importing entire script instead of function
🌐
Symbolab
symbolab.com › solutions › functions & line calculator › piecewise functions calculator
Piecewise Functions Calculator
Free piecewise functions calculator - explore piecewise function domain, range, intercepts, extreme points and asymptotes step-by-step
🌐
NumPy
numpy.org › doc › 2.2 › reference › generated › numpy.piecewise.html
numpy.piecewise — NumPy v2.2 Manual
Define the signum function, which is -1 for x < 0 and +1 for x >= 0. >>> x = np.linspace(-2.5, 2.5, 6) >>> np.piecewise(x, [x < 0, x >= 0], [-1, 1]) array([-1., -1., -1., 1., 1., 1.])
Top answer
1 of 1
2

There are quite a few issues here:

  • None of the keyword arguments (Constant, Variable, unit, Real) that you are passing to Symbol are things that are recognized by SymPy. The only one that is close is real, which should be lowercase (like Symbol('x', real=True)). The rest do nothing. If you want units, you should use the SymPy units module in sympy.physics.units. There is no need to specify if a symbol is constant or variable.

  • You have redefined Solar_Radius and gamma as numbers. That means that the Symbol definitions for those variables are pointless.

  • If you are using Python 2, make sure to include from __future__ import division at the top of the file, or else things like 1/2 and 5/3 will be truncated with integer division (this isn't an issue in Python 3).

  • range(0, x/c) doesn't make sense. range creates a list of numbers, like range(0, 3) -> [0, 1, 2]. But x/c is not a number, it's a symbolic expression.

  • Additionally, xi[x, t] = ... doesn't make sense. xi is a Symbol, which doesn't allow indexing and certainly doesn't allow assignment.

  • Don't mix numeric (math, mpmath, numpy, scipy) functions with SymPy functions. They won't work with symbolic expressions. You should use only SymPy functions. If you create a symbolic expression and want to convert it to a numeric one (e.g., for plotting), use lambdify.

What you want here is Piecewise. The syntax is Piecewise((expr, cond), (expr, cond), ..., (expr, True)), where expr is an expression that is used when cond is true ((expr, True) is the "otherwise" condition).

For your example, I believe you want

expr = Piecewise((0, t < x/c), (sy.exp(gamma*g*x/(2*c**2))*sy.besselj(0, (gamma*g/(2*c)*sy.sqrt(t**2 - (x/c)**2)))/2, t >= x/c))

If you want to turn this into a numeric function in x and t, use

xi = lambdify((x, t), expr)
🌐
Kitchin Research Group
kitchingroup.cheme.cmu.edu › blog › 2013 › 02 › 23 › Vectorized-piecewise-functions
Vectorized piecewise functions
def f2(x): 'fully vectorized version' x = np.asarray(x) y = np.zeros(x.shape) y += ((x >= 0) & (x < 1)) * x y += ((x >= 1) & (x < 2)) * (2 - x) return y print f2([-1, 0, 1, 2, 3, 4]) x = np.linspace(-1,3); plt.plot(x,f2(x)) plt.savefig('images/vector-piecewise-2.png') ... ... ... ... ... ... >>> [ 0. 0. 1. 0. 0. 0.] >>> [<matplotlib.lines.Line2D object at 0x043A4910>] A third approach is to use Heaviside functions.
🌐
Trkern
trkern.github.io › p.html
Piecewise Functions
This interactive will allow you to enter a piecewise function and view its graph. While normally pieces are not allowed to overlap, this interactive allows them to overlap so you can make drawings.