How to turn Rational to Real in Mathematica - wolfram-mathematica

I have some issue here which I don't know how to solve in a good way. For example, I want to use BaseForm[1/3, 3]. However, this does not do what I intended unless I input BaseForm[1/3.,3]. Given the data in Rational form, how to turn it to Real? I tried with Apply, it does not work. (Strange enough, uh? To me, Apply can always be used to change header.)
To this specific problem, I could have done something like BaseForm[1/3*1.,3], but it really isn't very nice.
Thanks for your help.

BaseForm takes a rational in base 10 to a rational in what ever base you want... so it does what you expect.
In[1]:= BaseForm[1/3,3]
Out[1]//BaseForm= Subscript[1, 3]/Subscript[10, 3]
And as you pointed out, giving it a Real number can be done like:
In[2]:= BaseForm[1/3.,3]
Out[2]//BaseForm= Subscript[0.1, 3]
The safest way to change things would be to define your own baseForm which is the same as BaseForm except for when it's given rational numbers:
baseForm[r_Rational,b_]:=BaseForm[N[r],b]
Then
In[3]:= baseForm[1/3,3]
Out[3]//BaseForm= Subscript[0.1, 3]
The less safe way (because you don't know what else it might break) is to redefine BaseForm
Unprotect[BaseForm];
BaseForm[r_Rational, b_] := BaseForm[N[r], b]
Protect[BaseForm];
and then use as normal.

I may be missing the subtlety of your request, but if you always want a real-number output, why not merely use N?
BaseForm[N[1/3], 3]
(* Out= 0.13 *)

Related

mathematica physical constants without units

It is helpful to use physical constants included in mathematica. Unfortunately they all include units. This provides errors when trying to integrate numerically. Is there a way just to get the value of a variable without any dimensions?
Thank you!
Martin
If e.g. c is the speed of light:
c = UnitConvert[Quantity["SpeedOfLight"]]
Then the obvious way would be to write:
c/Quantity["Meters"/"Seconds"]
Because that way, you're certain the unitless quantity you work with actually means something in m/s, not e.g. ft/hour. In other words: If you wrote c/Quantity["Feet"/"Hours"], the result would be the speed of light, in ft/hour, without a unit attached.
Alternatively, you could always write:
QuantityMagnitude[c]
Which just returns the magnitude, without the unit
Perhaps this will help
In[1]:= sol = UnitConvert[Quantity["SpeedOfLight"]]
Out[1]= 299792458 m/s
In[2]:= FullForm[sol]
Out[2]//FullForm= Quantity[299792458,Times[Meters,Power[Seconds,-1]]]
In[3]:= mysol = First[sol]
Out[3]= 299792458
In[4]:= FullForm[mysol]
Out[4]//FullForm= 299792458

Working with real functions in mathematica

In general, mathematica always assumes the most general case, that is, if I set a function
a[s_]:={a1[s],a2[s],a3[s]}
and want to compute its norm Norm[a[s]], for example, it will return:
Sqrt[Abs[a1[s]]^2 + Abs[a2[s]]^2 + Abs[a3[s]]^2]
However, if I know that all ai[s] are real, I can invoke:
Assuming[{a1[s], a2[s], a3[s]} \[Element] Reals, Simplify[Norm[a[s]]]]
which will return:
Sqrt[a1[s]^2 + a2[s]^2 + a3[s]^2]
Which is what I expect.
Problem happens when trying to, for example, derive a[s] and then (note the D):
Assuming[{a1[s], a2[s], a3[s]} \[Element] Reals, Simplify[Norm[D[a[s],s]]]]
Returns again a result involving absolute values - coming from the assumption that the numbers may be imaginary.
What is the way to overcome this problem? I want to define a real-valued function, and work with it as such. That is, for instance, I want its derivatives to be real.
I would use a custom function instead, e.g.
vecNorm[vec_?VectorQ] := Sqrt[ vec.vec ]
Then
In[20]:= vecNorm[D[{a1[s], a2[s], a3[s]}, s]]
Out[20]= Sqrt[
Derivative[1][a1][s]^2 + Derivative[1][a2][s]^2 +
Derivative[1][a3][s]^2]
Warning: I don't have much practical experience with this, so the examples below are not thoroughly tested (i.e. I don't know if too general assumptions can break anything I haven't thought of).
You can use $Assumptions to define permanent assumptions:
We could say that all of a1[s], a2[s], a3[s] are reals:
$Assumptions = {(a1[s] | a2[s] | a3[s]) \[Element] Reals}
But if you have e.g. a1[x] (not a1[s]), then it won't work. So we can improve it a bit using patterns:
$Assumptions = {(a1[_] | a2[_] | a3[_]) \[Element] Reals}
Or just say that all values of a[_] are real:
$Assumptions = {a[_] \[Element] Reals}
Or even be bold and say that everything is real:
$Assumptions = {_ \[Element] Reals}
(I wonder what this breaks)
AppendTo is useful for adding to $Assumptions and keeping previous assumptions.
Just like Assuming, this will only work for functions like Simplify or Integrate that have an Assumtpions option. D is not such a function.
Some functions like Reduce, FindInstance, etc. have an option to work only on the domain of Reals, Integers, etc., which assumes that all expressions and subexpressions they work with are real.
ComplexExpand[] and sometimes FunctionExpand[] may also be useful in similar situations (but not really here). Examples: ComplexExpand[Abs[z]^2, TargetFunctions -> {Sign}] and FunctionExpand[Abs'[x], Assumptions -> {x \[Element] Reals}].
Generally, as far as I know, there is no mathematical way to tell Mathematica that a variable is real. It is only possible to do this in a formal way, using patterns, and only for certain functions that have the Assumptions option. By "formal" I mean that if you tell it that a[x] is real, it will not know automatically that a'[x] is also real.
You could use ComplexExpand in this case albeit with a workaround. For example
ComplexExpand[Norm[a'[s], t]] /. t -> 2
returns
Sqrt[Derivative[1][a1][s]^2 + Derivative[1][a2][s]^2 + Derivative[1][a3][s]^2]
Note that doing something like ComplexExpand[Norm[a'[s], 2]] (or indeed ComplexExpand[Norm[a'[s], p]] where p is a rational number) doesn't work for some reason.
For older Mathematica versions there used to be an add-on package RealOnly that put Mathematica in a reals-only mode. There is a version available in later versions and online with minimal compatibility upgrades. It reduces many situations to a real-only solution, but doesn't work for your Norm case:

What does // mean in Mathematica?

Examples:
In
CT = Table[Prepend[10^4*x[range2] /.
NDSolve[{...series of equations here...}, {t, range1, range2},
MaxSteps -> 10000,
PrecisionGoal -> 11], delay],
{delay, delaymin, delaymax, 0.1}]; // Timing
what does it mean this // Timing after the semicolon?
In
Dρ = -I*((H0 + V).ρ - ρ.(H0 + V)) - Γ*ρ // Simplify;
And this // Simplify here?
I can't find this explanation anywhere!
Thanks in advance,
Thiago
This is Mathematica's postfix notation.
Basically x//f is the same as f[x]
Yes, argument // function is postfix function application.
Useful about it is that it has a different, lower binding power relative to prefix application (f # x).
In fact it is lower than most other things (exceptions include CompoundExpression ; and Set =), and therefore it can often be considered as "apply to everything before this."
You say: "I can't find this explanation anywhere!". I assume this means you are not aware of the documentation center that's right under your fingertips whenever you're using Mathematica.
All you have to do is to place your cursor on the // and press F1 and you'll get some sort of explanation, or a list with relevant (hopefully) matches. In this case the PostFix page, which is not extremely helpful. However, it has some links at the bottom (assuming you have versions 6, 7 or 8) that provide more insight, among which a link to the syntax overview page (click the Mathematica syntax link, or enter "guide/Syntax" in the search box).
expr // f is essentially equivalent to f[expr]. Sometimes, it's called postfix notation. I read expr // f as "pass the expression expr to the function f".
a // f
is, I believe, the same thing as
f[a]
(which incidentally, any sane mathematician I know would write as
f(a)
just as it is done in most computer languages.)
As others have mentioned, // is the postfix notation and expr//f means f[expr] in mathematica and f(expr) in math.
Although there might be more subtleties involved, my usage of // has often been in cases where I've started writing out an expression and then realized I wanted to operate a function on it. So instead of moving the cursor all the way back to type f#expr or f[expr], I can simply finish typing what I had in mind, and use expr//f.
Example:
Plot[Sin[x],{x,0,Pi}]
%//Export["test.pdf",#]&
The graphics is passed to the export function and is saved as test.pdf.
As your question has already got very good answers, I want to add just a clarification on usage.
The three expressions
Sin[x]
Sin#x
x // Sin
Are equivalent.
Although, to my knowledge, the last two can't be used with functions with more than one argument. So
Plot[Sin[x], {x, 0, Pi}]
Can't be invoked in prefix or postfix notation without tricks like
Sin[x] // Plot[#, {x, 0, Pi}] &
or
Plot[#, {x, 0, Pi}] &#Sin[x]
The prefix notation is usually seen when using simple functions like Sin#x or Sort#list, while most uses of the postfix involve a reasoning like "and now do whatever with this thing I got", for example
(Sin#x+ ...) // Timing
where you decided what to calculate, and then you also want it timed.
One more note:
Really there is much more under the scenes, as the priority of each of these functional constructs is different, but I think that is a much deeper subject and you have to experiment a little before going for subtleties.

how to set round-off precision in mathematica

I want to illustrate the stability of some numerical algorithms. I want to use Mathematica to round floating point numbers according to the usual rule, for example:
myRound[3/80.]=0.038 if I specify the precision to be 2-digit.
Another one
myRound[89/47.]=1.89
So given a precision number, how to write the myRound function? Please help. Many thanks.
You should look into NumberForm. For example:
NumberForm[89.0/47.0, 3]
Returns 1.89.
Acutally, it occurs to me that if you really want to illustrate round off issues, you should look into the ComputerArithmetic package. It's well documented, so I'll leave it at that.
I am not sure is this is what you would like:
In[34]:= customRound[x_Real] :=
Round[x, 10^Round[RealExponent[x]]*0.01]
In[35]:= customRound[3/80.]
Out[35]= 0.038
In[36]:= customRound[89/47.]
The function actually changes the number, as opposed to merely changing the way it is displayed.

How to prepend a column to a matrix?

Ok, imagine I have this Matrix: {{1,2},{2,3}}, and I'd rather have {{4,1,2},{5,2,3}}. That is, I prepended a column to the matrix. Is there an easy way to do it?
My best proposal is this:
PrependColumn[vector_List, matrix_List] :=
Outer[Prepend[#1, #2] &, matrix, vector, 1]
But it obfuscates the code and constantly requires loading more and more code. Isn't this built in somehow?
Since ArrayFlatten was introduced in Mathematica 6 the least obfuscated solution must be
matrix = {{1, 2}, {2, 3}}
vector = {{4}, {5}}
ArrayFlatten#{{vector, matrix}}
A nice trick is that replacing any matrix block with 0 gives you a zero block of the right size.
I believe the most common way is to transpose, prepend, and transpose again:
PrependColumn[vector_List, matrix_List] :=
Transpose[Prepend[Transpose[matrix], vector]]
I think the least obscure is the following way of doing this is:
PrependColumn[vector_List, matrix_List] := MapThread[Prepend, {matrix, vector}];
In general, MapThread is the function that you'll use most often for tasks like this one (I use it all the time when adding labels to arrays before formating them nicely with Grid), and it can make things a lot clearer and more concise to use Prepend instead of the equivalent Prepend[#1, #2]&.
THE... ABSOLUTELY.. BY FAR... FASTEST method to append or prepend a column from my tests of various methods on array RandomReal[100,{10^8,5}] (kids, don't try this at home... if your machine isn't built for speed and memory, operations on an array this size are guaranteed to hang your computer)
...is this: Append[tmp\[Transpose], Range#Length#tmp]\[Transpose].
Replace Append with Prepend at will.
The next fastest thing is this: Table[tmp[[n]]~Join~{n}, {n, Length#tmp}] - almost twice as slow.

Resources