0

I'm trying to make 3 columns in my .txt file to make it easier to read. This is the code:

file_out = open("Assignment1_Part1.txt", "w")
file_out.write(str(x) + str(fx(x, a)), + str(fx1(x, a)))
file_out.close()

Where x,fx, and fx1 each contain a ton of different values. I want the first value of x to line up with the first value of fx and fx1, however in the .txt file whats happening is all of the x values are typed out first, followed by all the fx, followed by all fx1, like so:

(x)(x)1(x)2 (fx)(fx)1(fx)2 (fx1)(fx1)1(fx1)2

whereas I want it to look like this:

(x) (fx) (fx1)

(x)1 (fx)1 (fx1)1

(x)2 (fx)2 (fx1)2

And so on. Thanks in advance!

edit: whole code

import numpy as np
import matplotlib.pyplot as plt

# Defining Functions ----



def fx(x, a):
    return np.sin(x**a - x**(1 / a) + a * x)


def gx(x, a):
    return a*(x)**(a-1) - (1/a)*x**((1/a) - 1) + a


def fx1(x, a):
    return gx(x, a) * (np.cos(x**a - x**(1 / a) + a * x))


# NR Method ----


def NR(x, function, deriv):
    return x - function/deriv


# Creating x values and defining a ----
x = np.arange(0.00, 5, 0.01)
a = 0.4 + (0223.0 / 25000.0)


# np.column_stack joins two arrays to make a table
ar1 = np.column_stack((x, fx(x, a)))
print(ar1)

plt.plot(x, fx(x, a))
plt.xlabel('x')
plt.ylabel('f(x)')
#plt.savefig("part1")
plt.savefig('part1')
# ar2 = np.column_stack((ar1,fx1(x,a)))
# print(ar2)

file_out = open("Assignment1_Part1.txt", "w")
file_out.write(str(x)+str(fx(x, a))+str(fx1(x, a)))
file_out.close()

Edit 2: Sorry for not making this clear, but the txt file is huge, like 240 lines, the assignment is the plot of a graph so it contains every x value and y value on the graph. This would make adding a newline after each value impossible

morgy2190
  • 3
  • 2

3 Answers3

1

Would do it like this, not with file open

import numpy as np

data = np.arange(0.00, 5, 0.01)

a = 0.4 + (0223.0 / 25000.0)
def fx(x, a):
    return np.sin(x**a - x**(1 / a) + a * x)


def gx(x, a):
    return a*(x)**(a-1) - (1/a)*x**((1/a) - 1) + a


def fx1(x, a):
    return gx(x, a) * (np.cos(x**a - x**(1 / a) + a * x))

import pandas as pd 

df = pd.DataFrame(columns=["x","fx","fx1"])
df['x'] = data
df['fx'] = fx(df['x'],a)
df['fx1'] = fx1(df['x'],a)
print(df)

df.to_csv("file_name.csv")

The dataframe will look like this (you can select what the delimiter between data is by sep param in to_csv, default is comma):

        x        fx        fx1
0    0.00  0.000000        inf
1    0.01  0.155553   6.545237
2    0.02  0.208523   4.429984
3    0.03  0.247846   3.529117
4    0.04  0.280304   3.001404
..    ...       ...        ...
495  4.95 -0.895714  10.722176
496  4.96 -0.763377  15.623705
497  4.97 -0.586145  19.655121
498  4.98 -0.374017  22.565874
499  4.99 -0.139202  24.166720
Ruli
  • 2,592
  • 12
  • 30
  • 40
  • Nice answer, clean. Upvote for CSV and steering well clear of arbitrary whitespace! – S3DEV Oct 29 '20 at 20:58
  • actually you should try with the actual code (definitions) because it returns arrays or sth – Matiiss Oct 29 '20 at 20:59
  • Edited it with actual OPs functions and data, there is no change in my part of code tho, will work just as fine :) – Ruli Oct 29 '20 at 21:03
0

here ya go its in gonna be in .txt file now:

import numpy as np
import matplotlib.pyplot as plt

# Defining Functions ----



def fx(x, a):
    return np.sin(x**a - x**(1 / a) + a * x)


def gx(x, a):
    return a*(x)**(a-1) - (1/a)*x**((1/a) - 1) + a


def fx1(x, a):
    return gx(x, a) * (np.cos(x**a - x**(1 / a) + a * x))


# NR Method ----


def NR(x, function, deriv):
    return x - function/deriv


# Creating x values and defining a ----
x = np.arange(0.00, 5, 0.01)
a = 0.4 + (0223.0 / 25000.0)


# np.column_stack joins two arrays to make a table
ar1 = np.column_stack((x, fx(x, a)))
# print(ar1)

plt.plot(x, fx(x, a))
plt.xlabel('x')
plt.ylabel('f(x)')
#plt.savefig("part1")
plt.savefig('part1')
# ar2 = np.column_stack((ar1,fx1(x,a)))
# print(ar2)
temp = []
c = 0
for i in range(len(fx(x, a))):
    str = f'{x[c]}, {fx(x, a)[c]}, {fx1(x, a)[c]}'
    temp.append(str)
    c += 1
with open("Assignment1_Part1.txt", "w") as file:
    file.write('\n'.join(temp))
Matiiss
  • 5,970
  • 2
  • 12
  • 29
0

(fake?) data

import numpy as np
x = np.arange(0.001, .1, 0.01)
a = 0.4 + (0223.0 / 25000.0)

Use zip to transpose the results of the three function calls.

data = zip(x,fx(x,a),fx1(x,a))

Create a list of strings from that data and write to a file

with open(the_file,'w') as f:
    f.writelines(f'{x},{y},{z}\n' for (x,y,z) in data)
wwii
  • 23,232
  • 7
  • 37
  • 77