# Output result in several columns

Dear Sage users, I have a simple function f(k,x)=Sin(kx). In Sage notebook, I would like to get an output of f(k,x) for x in [0..2*pi,step=0.01] and then for k in [1..10,step=4] (a nested loop). I prefer to get output in an txt-file in several columns as in the following (just numbers):

x    f(k1,x)    f(k2,x)    f(k3,x)

0        0            0            0

0.01   0.01      0.05     0.0899

...       ...           ...          ...

I have tried several codes but without success. I think that the problem of my code is not the Sage but my poor knowledge of Python.

Could somebody tell me how to get output in more correct form?

Firs line of my output is normal, But the next three columns are separated in a not preferred manner:

x=var('x')
html('<!--notruncate-->')
f=file("sage_sinkx.txt","w")
for  x in [0..2*pi,step=0.01]:
rows=n(x,digits=4),[n(sin(k*x), digits=3)  for k in [1..10,step=4]]
s=table(rows)
f.write(str(s)+ "\n")
print s
f.close()


Let me know please if anybody could help.

Thank to all.

edit retag close merge delete

Sort by » oldest newest most voted

Here is an option using the excel-tab dialect in python.

with open('fun.csv', 'w') as f1:

writefile = csv.writer(f1, dialect='excel-tab')

for  x in [0..2*pi,step=0.01]:
result=[n(x,digits=4)]+[n(sin(k*x), digits=3)  for k in [1..10,step=4]]
writefile.writerow(result)

more

call314: Thank you for your rapid response.Your suggestion has solved my problem.

In that case, be sure to mark this answer as accepted by clicking the check mark icon, so that other users will know if they search for this question - thanks!

Ok. The final point in my question could be the following: In order to import output data to such software as Grace, it would be better to use other dialect delimiter=' ' instead of excel-tab, and also use use fun.dat instead of fun.csv. It doesn't make any difference and output file is the same. Then grace can read DAT file.

Thanks for that point; I do not know Grace but that could be helpful to others who do use it.