Skip to content

Instantly share code, notes, and snippets.

@jdbrice
Last active January 31, 2019 21:29
Show Gist options
  • Save jdbrice/2e0b72b3a282f453fd3462d77c4c5567 to your computer and use it in GitHub Desktop.
Save jdbrice/2e0b72b3a282f453fd3462d77c4c5567 to your computer and use it in GitHub Desktop.
Makes numpy linspace ranges from the shell, even chain together with commas
#!/usr/bin/env python
import numpy
import sys
if len(sys.argv) < 4:
print( "Usage: linspace start stop step [, endpoint, ndecimals]" )
exit()
if not sys.stdin.isatty():
for line in sys.stdin:
sys.stdout.write(line.strip())
start = float(sys.argv[1])
stop = float(sys.argv[2])
nbins = int(sys.argv[3])
ndigits = 2;
endpoint = True
if len( sys.argv ) > 4:
endpoint = sys.argv[4].lower() == 'true'
# also support 0,1 for false/true
if sys.argv[4] == "0":
endpoint = False
if sys.argv[4] == "1":
endpoint = True
if len( sys.argv ) > 5:
ndigits = sys.argv[5]
vals = ""
fmt = "%0." + str(ndigits) + "f"
for v in numpy.linspace( start, stop, nbins, endpoint ):
vals = vals + fmt % v + ", "
if not sys.stdin.isatty() :
print(", " + vals[:-2])
else :
print(vals[:-2])
#Usage Example:
$> linspace 0 5 6 False 3 | linspace 5 6 10 1 1
0.000, 0.833, 1.667, 2.500, 3.333, 4.167, 5.0, 5.1, 5.2, 5.3, 5.4, 5.6, 5.7, 5.8, 5.9, 6.0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment