Ask Your Question

Output result in several columns

asked 2015-12-10 10:44:45 -0500

Chuvac gravatar image

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:

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]]
     f.write(str(s)+ "\n")
     print s

Let me know please if anybody could help.

Thank to all.

edit retag flag offensive close merge delete

1 answer

Sort by » oldest newest most voted

answered 2015-12-10 13:28:28 -0500

calc314 gravatar image

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]]
edit flag offensive delete link more


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

Chuvac gravatar imageChuvac ( 2015-12-10 14:34:51 -0500 )edit

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!

kcrisman gravatar imagekcrisman ( 2015-12-10 20:53:58 -0500 )edit

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.

Chuvac gravatar imageChuvac ( 2015-12-11 01:10:16 -0500 )edit

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

kcrisman gravatar imagekcrisman ( 2015-12-11 10:04:15 -0500 )edit

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

Question Tools

1 follower


Asked: 2015-12-10 10:42:04 -0500

Seen: 76 times

Last updated: Dec 10 '15