Skip to content
Advertisement

How can i make this calculations from file?

I have a file contains two columns and need to apply this equation on them like

x    y  

1.2  6.8
2.5  7.0
3    8
4    9
5    10

the equation is

de = sqrt((xi-xj)^2-(yi-yj)^2)

it means the result will be a column

row1 = sqrt((x1-x2)^2-(y1-y2)^2)

row2 = sqrt((x1-x3)^2-(y1-y3)^2)

and do this equation for each point x1 to other points and y1 for other points until finished then start to calculate

row 6 = sqrt((x2-x3)^2-(y2-y3)^2)

row 7 = sqrt((x2-x4)^2-(y2-y4)^2)

and do this equation for each point x2 to other points and y2 for other points until finished and so on until finished all x and y and store the result in a file

I tried to do this by using 2 arrays and stored the numbers on them then make calculations but the data is too huge and the array will be the wrong choice .. how can I do this in python .. reading from file the I and j for each value

my tries and sorry if it’s too bad

import math
with open('columnss.txt', 'r', encoding='utf-8') as f:
      for line in f: 
           [x, y] = (int(n) for n in line.split())
           d = math.sqrt(((x[0] - y[0])**2) + ((x[1] - y[1])** 2)) 
           with open('result.txt', 'w', encoding='utf-8') as f1:
                  f1.write( str(d) + 'n')

i got

ValueError: invalid literal for int() with base 10: '-9.2'

I did the calculations in excel but trying to use python for it too Should I put each column in a separate file to be easier for catching numbers or can I do this with the same file?

*

Advertisement

Answer

You need to loop through the input file twice. The second loop can skip all the lines that are before the line from the first loop.

If you could load the file contents into a list or array, you could do this more easily by iterating over indexes rather than skipping lines.

Also, you should only open the output file once. You’re overwriting it every time through the loop.

import cmath

with open('columnss.txt', 'r', encoding='utf-8') as f1, open('columnss.txt', 'r', encoding='utf-8') as f2, open('result.txt', 'w', encoding='utf-8') as outfile:
    for i1, line in enumerate(f1):
        x1, y1 = (float(n) for n in line.split())
        f2.seek(0)
        for i2, line in enumerate(f2):
            if i1 < i2:
                x2, y2 = (float(n) for n in line.split())
                print(cmath.sqrt((x1-x2)**2-(y1-y2)**2), file=outfile)
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement