-6

I have a file(Data.txt), which contains data like (two column data)

0.105785959943        9.75133617601e+15
0.111906693211        9.03309900398e+15
0.118381569654        9.10020956844e+15
0.125231079854        9.92284743442e+15
0.132476899971        8.90313525209e+15
0.140141960337        8.94055824107e+15
0.148250518026        9.26206609674e+15
0.156828233614        8.91802025262e+15

The file may contain 100 lines. Let me call the values in first column as r_i and second column as d_i (i may change from 0 to 100). My problem is to write a code to compute C*(r_(i+1)-r_i)^3 * d_i, where C is a constant.

And also I want to write these data into a new file containing 3 columns, in which the third column should be our new computed data.

How can I achieve this? Does any body know how to solve this problem?

Robᵩ
  • 163,533
  • 20
  • 239
  • 308
R S John
  • 507
  • 2
  • 9
  • 16

4 Answers4

0

For reading the files in Python, take a look at here. For writing output to file, take a look here.

Community
  • 1
  • 1
SKPS
  • 5,433
  • 5
  • 29
  • 63
0
#include <iostream>

int main(int, char*[]) {
  const double C = 1;
  double rp, dp;
  double r, d;

  std::cin >> rp >> dp;
  while (std::cin.good()) {
    std::cin >> r >> d;
    if (std::cin.good()) {
      double t = r - rp;
      double v = C * t * t * t * dp;
      std::cout << rp << " " << dp << " " << v << std::endl;
      rp = r; dp = d;
    }
  }
  std::cout << rp << " " << dp << " " << 0 << std::endl;

  return 0;
}
Adam Burry
  • 1,904
  • 13
  • 20
0

awk is ideal for this type of calculations:

awk -v c="$c" '{if (s) print o, c*($1-r)^3*d;o=$0;r=$1;d=$2;s=1}' file

where c is a shell variable

user000001
  • 32,226
  • 12
  • 81
  • 108
0

Even though 5 persons down voted my question, I found my on way to solve the problem. Here is the code which I used. It is written in Python.

enter codefrom numpy import *
from math import *
import operator

f = open('Data_Genergy_26.txt', 'r')
lines = f.readlines()
# initialize some variable to be lists:
r = []
ro = []
E =[]

# scan the rows of the file stored in lines, and put the values into some variables:
for line in lines:
    p = line.split()
    r.append(float(p[0]))
    ro.append(float(p[1]))
#Subtracting the current and previous item in a list
def foo(it):
    it = iter(it)
    t = it.next()
    for s in it:
        yield t, s
        t = s        
list(foo(r))
E=[x[1] - x[0] for x in foo(r)]
#print E
#Cubing all elements in a list
def cube(E):
    return [i ** 3 for i in E]
#print cube(E)
#computing total energy
z =[a*b for a,b in zip(cube(E),ro)]
z[:] = [x*4/3*pi for x in z] 
z.append(0.0) #for making r, ro, and z of same dimension
#print z     

DataOut = column_stack((r,ro,z))
savetxt('output.dat', DataOut)

If there is any better way to implement this please inform me. Thanks

R S John
  • 507
  • 2
  • 9
  • 16