Add up sum in file in scientific formulation in a shell script
ProgrammingThis forum is for all programming questions.
The question does not have to be directly related to Linux and any language is fair game.
Notices
Welcome to LinuxQuestions.org, a friendly and active Linux Community.
You are currently viewing LQ as a guest. By joining our community you will have the ability to post topics, receive our newsletter, use the advanced search, subscribe to threads and access many other special features. Registration is quick, simple and absolutely free. Join our community today!
Note that registered members see fewer ads, and ContentLink is completely disabled once you log in.
If you have any problems with the registration process or your account login, please contact us. If you need to reset your password, click here.
Having a problem logging in? Please visit this page to clear all LQ-related cookies.
Get a virtual cloud desktop with the Linux distro that you want in less than five minutes with Shells! With over 10 pre-installed distros to choose from, the worry-free installation life is here! Whether you are a digital nomad or just looking for flexibility, Shells can put your Linux machine on the device that you want to use.
Exclusive for LQ members, get up to 45% off per month. Click here for more info.
p.bar Creates bar charts
p.binit Assigns data to 2 dimensional bin structure
p.cat Rearrages columnar data into key,x,y format
p.catToTable Create a table from data in key,x,y format
p.cdf Plots the cumulative distribution
p.cl An awk-like math utility
p.color Makes color scatter plots
p.cumsum Computes the cumulative sum of inputs
p.datetime Converts text-based time stamps to seconds from an epoch
p.dedup Removes duplicate keys
p.distribute Distribute jobs across computers efficiently
p.exec Sequentially run commands read from stdin
p.gps2utc Convert gps time to utc time
p.grab Grab columns from a file with python-like indexing
p.grabHeader Extract the commented header from a file
p.groupStat Perform statistics over keyed subgroups of input
p.hist Plots a histogram
p.htmlWrap Create an html wrapper for images in a directory
p.interp Does polynomial interpolation
p.join Join two files on specified key columns
p.link Link to files based on specified key columns
p.linspace Generate a linear spaced sequence of numbers
p.map Plot points on a map
p.medianFilter Runs data through a median filter
p.minMax Find min/max values in specified data column
p.multiJoin Join multiple files together based on key
p.normalize Normalizes input data
p.parallel Run commands in parallel
p.parallelSSH Run commands in parallel across several machines
p.plot Plot points on a graph
p.quadAdd Add all columns from stdin in quadrature
p.quantiles Compute quantiles from input data
p.rand Generate a sequence of random numbers
p.rex Bring python rex to the command line
p.scat Make a scatter plot of input data
p.sed A sed-like utility with python syntax
p.shuffle Randomly shuffle rows of data
p.smooth Smooth data
p.sort Sort data based on specified keys
p.split Split data based on a supplied delimeter
p.strip Remove comments and/or nans from rows
p.tableFormat Nicely format input columns in a table format
p.template Bring jinja templates to the command line
p.utc2gps Convert utc time to gps time
p.utc2local Convert utc time to local time given a lon
p.cumsum
will do this
It is some NASA code that comes in handy from time to time
bash's mapfile command loads the lines from the file into an array. The '*' index expansion prints the entire array with the first character of IFS between each entry. Since bash doesn't have floating point arithmetic built-in we have to use an external command like bc to to the actual calculation. Finally, doing the operation inside a (..) subshell means we don't have to do anything to restore the original IFS setting afterwards.
In the second version I sent the output through the shell's built-in printf to convert it to exponential notation. With the proper configuration we could certainly get bc to output it like that directly, but I'm not familiar with how to do it, and I'm too lazy right now to look it up.
% ./s1
Environment: LC_ALL = C, LANG = C
(Versions displayed with local utility "version")
OS, ker|rel, machine: Linux, 2.6.26-2-amd64, x86_64
Distribution : Debian GNU/Linux 5.0.8 (lenny)
bash GNU bash 3.2.39
numsum (num-utils) 0.5-9
-----
Input data file data1:
5.4654654E+1 1
5.4654654E+0 2
5.4654654E-1 3
-----
Results, column sum, select column 1:
60.66666594
-----
Results, column sum, all columns:
60.66666594 6
The package was in the Debian repository. If not in yours, see the comment at the beginning of the script for the URL. The utilities are written in perl.
O.K., here's another solution using my current favorite language, pure:
Code:
#!/bin/bash
data=(5.4654654E+1
5.4654654E+0
5.4654654E-1
)
# pure wants a comma-delimited vector, so add a comma after each element
# except the last one.
for ((i=0;i<((${#data[*]}-1));++i))
do
data[i]="${data[i]},"
done
# The "foldl" function applies the 2 argument function in the second argument to the values in the fourth
# argument (a vector) in turn, from the left, using the third argument as the initial first argument, and
# the result as the first argument for every successive argument.
sum=$(echo "foldl (+) 0.0 [${data[*]}];" | pure -q)
echo "Total = ${sum}"
LinuxQuestions.org is looking for people interested in writing
Editorials, Articles, Reviews, and more. If you'd like to contribute
content, let us know.