I have a mathematica file with an algorithm that feeds another program with data.
my problem is that some times (randomly) the output is in fraction instead of decimal. The other program (java) does not read fractions, so I have to feed it with decimal numbers.
One solution is to use the N[.]
function before it output, but this is really painful procedure. Is there any setting in mathematica forcing it to return as output only decimals?
2 Answers
Two things might help you here:
- Make sure all your input is in floating point (
Real
) form, notInteger
s orRational
. You might find this tutorial helpful. I am willing to bet that the cases where you get a fraction are not really random. - If wrapping your output in
N
is unacceptable to you for some reason, you could instead use a rule once you have your output:data /. x_Rational :> N@x
. This will almost certainly be slower thanN
.
For example:
{1/2, 256/225, 0.6} /. x_Rational :> N@x
(* output is {0.5, 1.13778, 0.6}*)
N
is Listable
, so the following also works:
N[{1/2, 256/225, 0.6}]
-
$\begingroup$ first of all thank you for your reply! I will check the tutorial u sent me. I was overexaggerating when i said randomly, but frankly, i give an initial input of 5 variables in my algorithm, and i get hundreds of outputs, and the percentage of getting fractions instead of decimal numbers is not greater than 1% based on my hundreds and hundreds of tests. nevertheless, once i get fraction, the second program is useless (java). The second solution you suggest seems to be similar to the N[.] function, with respect to the editing i have to do in my code. i was wondering if there was a setting hidden $\endgroup$– Fierce82Aug 1, 2012 at 13:59
-
1$\begingroup$ As long as 1 value is MachinePrecision the output will be that too, isn't it? $\endgroup$ Aug 1, 2012 at 14:53
You can use $Post
:
If you set $Post
to N
, N
is applied to the output of every evaluation:
Cos[Pi/4]
$Post = N;
Cos[Pi/4]
(* 0.707107 *)
To restore $Post
to its default value, use
$Post =.
N
at the very last stage before sending the output to Java. $\endgroup$2
instead of2.
or2`
$\endgroup$