1
$\begingroup$

since I am new to Wolfram Mathematica I am wondering if somebody can help me with my problem. (it is simple I guess)

Basically I would like to extract the data from a function I defined in Mathematica an write this data to a output file (for instance a .dat file)

Here's my function:

w[x_]=0.00142878 Sin[3.14159 x]

Now I would like to fill the first column of the output-file with the data of w. Therefore I did the following loop and to show you the results I displayed the output.

For[x = 0.0, x <= 1, x += 0.2, PutAppend[w[x], "w.dat"]]

FilePrint["w.dat"]
0.
0.0008398150100260654
0.0013588492304845074
0.0013588492304845074
0.0008398150100260655
1.7497491811730056*^-19

My question is how it is possible to modify the output of w that:

  1. all the results have the same number of digits and

  2. to rewrite the result to ...E-19 instead of ...*^-19.

Thank you guys in advance!

$\endgroup$

1 Answer 1

3
$\begingroup$

Update

Control the number of digits

format[number_, digits_ : 4] :=
 StringReplace[
  TextString[
   EngineeringForm[number, digits, ExponentFunction -> (If[-10 < # < 10, Null, #] &)]],
  {".*10^" -> "E", "*10^" -> "E"}]

Table[format[w[x]], {x, 0, 1, .2}]
(* {"0.", "0.0008398", "0.001359", "0.001359", "0.0008398", "1.75E-19"} *)

Table[format[w[x], 3], {x, 0, 1, .2}]
(* {"0.", "0.00084", "0.00136", "0.00136", "0.00084", "1.75E-19"} *)

Here is one way to do it

data = Table[StringReplace[ToString@FortranForm@w[x], "e" -> "E"], {x, 0, 1, .2}]
Export["data.dat", data, "Text"]

You might also want to replace 3.14159 with Pi.

$\endgroup$
5
  • $\begingroup$ Thank you Rohit, that worked very well. The only thing I would also like to know, is how I can adjust the number of digits? Can you also help me with that? $\endgroup$
    – WM_noob5
    Commented Jun 24, 2020 at 5:28
  • $\begingroup$ It would be nice if somebody can help me to modify the data of w so that I just export this data set with eg. four digits of each value? $\endgroup$
    – WM_noob5
    Commented Jun 24, 2020 at 15:52
  • $\begingroup$ Try using NumberForm for more control over the number of digits. $\endgroup$ Commented Jun 24, 2020 at 16:35
  • $\begingroup$ @WM_noob5 Added a way to control number of digits. Not sure if that is what you were looking for. $\endgroup$ Commented Jun 24, 2020 at 18:43
  • $\begingroup$ @RohitThat was my bad. I am embarrassed to say that I've only just seen your comment on the control of the digits by now. First I just saw the things you wrote beneath "Here is one way to do it"... Thank you so much, you really helped me a lot $\endgroup$
    – WM_noob5
    Commented Jun 25, 2020 at 6:47

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.