6
$\begingroup$

I started working on Mathematica today. I'm trying to save the result of a loop in a file as a column, very simple to do, but hard for someone who doesn't know Mathematica syntax. Here is my code:

For[i = 1/10, i <= 4, i += (1/1000), 
    l = NIntegrate[(-1 + 0.707106781186547`/(-x^2 E^-x^2 + 0.5`)^0.5`)/x, {x, ∞, i}];
    Save["data.dat",l]
]

but obviously, this code is not working, it seems Save only works with strings. I have tried data streams, but I'm getting aborted each time I try.

How can I save the output from NIntegrate into a data file, in a loop?

$\endgroup$
1
  • $\begingroup$ Changed the data.dat for a string with the same name and It's working, but the file has in each row a l=value. Is there a way to just save the value? $\endgroup$
    – nosumable
    Jul 22, 2022 at 2:49

1 Answer 1

6
$\begingroup$

It is better to avoid For loops. And why not just use Export? And try to not use l for variable. Not a good choice as it looks like 1.

SetDirectory[NotebookDirectory[]]
ClearAll[x];
range = Range[1/10,4,1/10];
data  = NIntegrate[(-1+0.707106781186547`/(-x^2 E^-x^2+0.5`)^0.5`)/x,{x,Infinity,#}]&/@range;
Export["data.txt",data]

This is how the file looks like

enter image description here

Update

For Fortran format use

SetDirectory[NotebookDirectory[]]
ClearAll[x];
range = Range[1/10,4,1/10];
data  = NIntegrate[(-1+0.707106781186547`/(-x^2 E^-x^2+0.5`)^0.5`)/x,{x,Infinity,#}]&/@range;
data  = FortranForm[#]&/@data ;

Export["data.txt",data]

The file looks like

enter image description here

$\endgroup$
5
  • $\begingroup$ Hi, u are totally right, those mistakes are from a noob like me! By the way, I need the last values without that format because they are not readable in other languages like python, for example. Is there an easy way to change that? $\endgroup$
    – nosumable
    Jul 22, 2022 at 3:02
  • 2
    $\begingroup$ I do not understand what you mean by I need the last values without that format ? Can you give an example of what you mean? Do you mean Python does not understand -5.626766190483531*^-8 ? $\endgroup$
    – Nasser
    Jul 22, 2022 at 3:03
  • $\begingroup$ Sure, those values are not readable in other languages like python (number*^ exponent) Python functions struggle with that syntax. Is there a way to write those values for example like 1.0232e-4, which is readable in python? $\endgroup$
    – nosumable
    Jul 22, 2022 at 3:09
  • 2
    $\begingroup$ @nosumable update for Fortran format. Hopefully Python can read it now. $\endgroup$
    – Nasser
    Jul 22, 2022 at 3:19
  • 1
    $\begingroup$ Thanks! U are awesome, that is what I was searching too! Have a good day. $\endgroup$
    – nosumable
    Jul 22, 2022 at 3:21

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.