-6

我有一个文件(Data.txt),其中包含(两列数据)之类的数据

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

该文件可能包含 100 行。让我将第一列中的值称为r_i,将第二列中的值称为d_ii可能会从0变为100)。我的问题是编写一个代码来计算 C*(r_(i+1)-r_i)^3 * d_i,其中C是一个常数。

而且我想将这些数据写入一个包含 3 列的新文件中,其中第三列应该是我们新的计算数据。

我怎样才能做到这一点?有没有人知道如何解决这个问题?

4

4 回答 4

0

awk 非常适合这种类型的计算:

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

其中 c 是一个 shell 变量

于 2013-08-30T16:19:23.507 回答
0

要阅读 Python 中的文件,请查看此处。要将输出写入文件,请查看此处

于 2013-08-30T15:17:56.187 回答
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;
}
于 2013-08-30T15:19:52.827 回答
0

尽管有 5 个人对我的问题投了反对票,但我还是找到了解决问题的方法。这是我使用的代码。它是用 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)

如果有任何更好的方法来实现这一点,请告诉我。谢谢

于 2013-08-31T08:58:49.840 回答