5 ms·
Throw this in your ~/bin as a script named math: #!/bin/sh scale=4 # results will print to the 4th decimal echo "scale=$scale; $@" | bc -l Now you can d
by sillysaurus3 9y ago
Throw this in your ~/bin as a script named math:
#!/bin/sh
scale=4 # results will print to the 4th decimal
echo "scale=$scale; $@" | bc -l
Now you can do math.
$ math '1+1'
2
$ math '2/3'
.6666
This is especially useful in shell scripts with interpolated variables:
x=10
x=`math $x - 1`
- xelxebar 9y agoAlternatively, you could use an alias: # .bashrc alias bc='bc --mathlib' and a .bcrc file: # .bcrc scale = 4 Actually, this is what my .bcrc looks like: scale = 39 k_c = 299792458 # Speed of Light k_g = 6.67384 * 10^-11 # Gravitation k_atm = 100325 # Atmospheric pressure k_h = 6.62606957 * 10^-34 # Planck's constant k_hbar = 1.054571726 * 10^-34 # H Bar k_mu = 1.256637061 * 10^-6 # Vacuum permeability k_ep = 8.854187817 * 10^-12 # Vacuum permittivity k_epsilon = 8.854187817 * 10^-12 # Vacuum permittivity k_e = 1.602176565 * 10^-19 # Elementary charge k_coulomb = 8.987551787 * 10^9 # Coulomb's constant k_me = 9.10938294 * 10^-31 # Rest mass of an electron k_mp = 1.672621777 * 10^-27 # Rest mass of a proton k_n = 6.02214129 * 10^23 # Avogadro's number k_b = 1.3806488 * 10^-23 # Boltzmann's constant k_r = 8.3144621 # Ideal gas constant k_si = 5.670373 * 10^-8 # Stefan-Boltzmann constant k_sigma = 5.670373 * 10^-8 # Stefan-Boltzmann constant k_mt = 5.97219^24 # Mass of Earth (Tierra) k_rt = 6.371 * 10^6 # Mean radius of Earth (Tierra) pi = 3.1415926535897932384626433832795028841968 # requires --mathlib define t(x) { return s(x)/c(x); } define as(x) { return 2*a(x/(1+sqrt(1-x^2))); } define ac(x) { return 2*a(sqrt(1-x^2)/(1+x)); } define at(x) { return a(x); } define csc(x) { return 1/s(x); } define sec(x) { return 1/c(x); } define cot(x) { return c(x)/s(x); }
- schoen 9y agoIt's not nearly as flexible as bc overall, but GNU units has lots more constants built-in and also trig functions. I checked and it has all of the ones that you mentioned, sometimes under slightly different names. I was surprised that e is defined the elementary charge rather than Euler's constant!
- chubot 9y agoThat might be useful if you want floating point math, but most shell scripts can just use the integer math in shell: $ x=10 $ echo $((x - 1)) 9 Though if I need to do a floating point calculation at the shell, I start python or R, which both have their own interactive shells (with the same readline interface, which I like).