physical constants with subscripts in mathematica - wolfram-mathematica

I have a little Problem. I have searched for quite a while but haven't found an answer (help, I'm a beginner).
I want to make my own Notebook for physical calculations in mathematica 9. The notebook should be easy to use and one should be able to get an overview quickly (reason I don't want to use quantity every single time). I want to display my equations just like in a Textbook. My problem are the subscripts which I need for the ElectronMass for example. They need to be a Symbol, because I want to protect those values. But it doesn't work. I can change m and get a different value for Electronmass. Here's my notebook:
Needs["Notation`"];
Symbolize[ParsedBoxWrapper[SubscriptBox["_", "_"]]]
Subscript[m, e] = Quantity["ElectronMass"];
Subscript[m, p] = Quantity["ProtonMass"];
Subscript[m, n] = Quantity["NeutronMass"];
Protect[Subscript[m, el], Subscript[m, p], Subscript[m, n]];
so far so good... but then this happens...
In[19]:= m = 5
Out[19]= 5
In[20]:= Subscript[m, e ]
Out[20]= Subscript[5, e]
instead I would want
In[20]:= Subscript[m, e ]
Out[20]= Subscript[m, e]
just treating Subscript[m, e] independently from anything which has to do with "m" or "e"
thanks for the help

An easy work around is simply to protect all symbols you want to use, so instead of
Protect[Subscript[m, el], Subscript[m, p], Subscript[m, n]];
You need write
Protect[m,el,n];
That way once you set the values
Subscript[m, n] = 2;
Subscript[m, el] = 4;
later when evaluating them you are guaranteed to be returned the correct values. As a quick note, you might like to redefine the subscript for some motive, such as
Subscript[a_, b_] := a[b]

In addition to Artur's method you could set HoldAll on Subscript which will prevent evaluation of these Symbols. This should not be done lightly as it will affect all uses of Subscript but it may be exactly what you want if you desire this behavior to be general.
SetAttributes[Subscript, HoldAll]
m = 5; e = 3;
Subscript[m, e]
(* Out= *) Quantity["ElectronMass"]
Dedicated StackExchange site:

In addition to the excellent Hold (your breath) and Protect (your precious variables) answers you got so far, I rather suggest you stop and think for a moment.
Is this a limitation/quirk of MMA or rather a limitation of the logic/style of your paper/notebook?
After all: you go at great lengths to define m's with subscripts to indicate specific masses. Then why on earth do you want to define a quantity (constant, perhaps) just m without subscrpts?
Is it a mass? then give it a subscript to indicate what kind of mass it is.
Is it not a mass? Then call it something else. Use a longer - more descrptive - variable name, or mm if you have really run out of creativity.
In general do not confuse your readers with similar symbols having widely different meanings.
Also , I would not type
Symbolize[ParsedBoxWrapper[SubscriptBox["_", "_"]]]
since this is way too general.
I would type
Symbolize[ParsedBoxWrapper[SubscriptBox["m", "_"]]]
which restricts the kind of physical objects with pretty subscripts.
Of course, you can always later add
Symbolize[ParsedBoxWrapper[SubscriptBox["q", "_"]]]
if you need to describe other subscripted quantities (say charges).,

Related

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:

Equation Threading: Why the default behavior?

I recently rediscovered a small package by Roman Maeder that tells Mathematica to automatically thread arithmetic and similar functions over expressions such as x == y. Link to Maeder's package.
First, to demonstrate, here's an example given by Maeder:
In[1]:= Needs["EqualThread`"]
Now proceed to use the threading behavior to solve the following equation for x 'by hand':
In[7]:= a == b Log[2 x]
In[8]:= %/b
Out[8]:= a/b == Log[2 x]
Now exponentiate:
In[9]:= Exp[%]
Out[9]= E^(a/b) == 2 x
And divide through by 2:
In[10]:= %/2
Out[10]= (E^(a/b))/2 == x
Q: From a design perspective, can someone explain why Mathematica is set to behave this way by default? Automatically threading seems like the type of behavior a Mathematica beginner would expect---to me, at least---perhaps someone can offer an example or two that would cause problems with the system as a whole. (And feel free to point out any mathematica ignorance...)
Seems natural when thinking of arithmetic operations. But that is not always the case.
When I write
Boole[a==b]
I don't want
Boole[a] == Boole[b]
And that is what Maeder's package does.
Edit
Answering your comment below:
I noticed that Boole[] was added in v.5.2, whereas Maeder's package was authored for v.3. I guess the core of my question still revolves around the 'design' issue. I mean, how would one get around the issue you pointed out? To me, the clearest path would be declaring something about variables you're working with, no? -- What puzzles me is the way you can generally only do this with Assumptions (globally or as an option to Simplify, etc). Anyone else think it would be more natural to have a full set of numerical Attributes? (in this regard, the Constant Attribute is a tease)
My answer is by no means a critic to Maeder's package, which is nice, but a statement that it should not be the mainstream way to treat Equal[ ] in Mma.
Equal[ ] is a function, and not particularly easy to grasp at first:
returns True if lhs and rhs are identical
returns False if lhs and rhs are determined to be unequal by comparisons between numbers or other raw data, such as strings.
remains unevaluated when lhs or rhs contains objects such as Indeterminate and Overflow.
is used to represent a symbolic equation, to be manipulated using functions like Solve.
The intent of Maeder's package, which I understand is well aligned with yours, is to give to the expression lhs == rhs the same meaning and manipulation rules humans use when doing math.
In math, equality is an equivalence relation, imposing a partial order in a set, and an equation is an assertion that the expressions are related by this particular relation.
Compare these differences with other Mma "functions". Sin[x] is in Mma, and in usual math the same thing (well, almost), and the same can be said of most Mma beasts. There are a few Mma constructs, however, that do not hold that exact isomorphism to math concepts: Equal, SameQ, Equivalent, etc. They are the bridge from the math world to the programming world. They are not strict math concepts, but modified programming concepts to hold them.
Sorry if I got a little on the philosophical side.
HTH!
I guess it is partly because the behavior can not be extended over to inequalities. And also because the behavior should make sense both when equalities become evaluated:
Would be nice:
In[85]:= Thread[Power[a == b, 2], Equal]
Out[85]= a^2 == b^2
In[86]:= Thread[Power[a == b, c == d], Equal]
Out[86]= a^c == b^d
but:
In[87]:= Thread[Power[a == b, c == d] /. {c -> 2, d -> 2}, Equal]
Out[87]= a^True == b^True

How to turn Rational to Real in 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 *)

Mathematica Notation and syntax mods

I am experimenting with syntax mods in Mathematica, using the Notation package.
I am not interested in mathematical notation for a specific field, but general purpose syntax modifications and extensions, especially notations that reduce the verbosity of Mathematica's VeryLongFunctionNames, clean up unwieldy constructs, or extend the language in a pleasing way.
An example modification is defining Fold[f, x] to evaluate as Fold[f, First#x, Rest#x]
This works well, and is quite convenient.
Another would be defining *{1,2} to evaluate as Sequence ## {1,2} as inspired by Python; this may or may not work in Mathematica.
Please provide information or links addressing:
Limits of notation and syntax modification
Tips and tricks for implementation
Existing packages, examples or experiments
Why this is a good or bad idea
Not a really constructive answer, just a couple of thoughts. First, a disclaimer - I don't suggest any of the methods described below as good practices (perhaps generally they are not), they are just some possibilities which seem to address your specific question. Regarding the stated goal - I support the idea very much, being able to reduce verbosity is great (for personal needs of a solo developer, at least). As for the tools: I have very little experience with Notation package, but, whether or not one uses it or writes some custom box-manipulation preprocessor, my feeling is that the whole fact that the input expression must be parsed into boxes by Mathematica parser severely limits a number of things that can be done. Additionally, there will likely be difficulties with using it in packages, as was mentioned in the other reply already.
It would be easiest if there would be some hook like $PreRead, which would allow the user to intercept the input string and process it into another string before it is fed to the parser. That would allow one to write a custom preprocessor which operates on the string level - or you can call it a compiler if you wish - which will take a string of whatever syntax you design and generate Mathematica code from it. I am not aware of such hook (it may be my ignorance of course). Lacking that, one can use for example the program style cells and perhaps program some buttons which read the string from those cells and call such preprocessor to generate the Mathematica code and paste it into the cell next to the one where the original code is.
Such preprocessor approach would work best if the language you want is some simple language (in terms of its syntax and grammar, at least), so that it is easy to lexically analyze and parse. If you want the Mathematica language (with its full syntax modulo just a few elements that you want to change), in this approach you are out of luck in the sense that, regardless of how few and "lightweight" your changes are, you'd need to re-implement pretty much completely the Mathematica parser, just to make those changes, if you want them to work reliably. In other words, what I am saying is that IMO it is much easier to write a preprocessor that would generate Mathematica code from some Lisp-like language with little or no syntax, than try to implement a few syntactic modifications to otherwise the standard mma.
Technically, one way to write such a preprocessor is to use standard tools like Lex(Flex) and Yacc(Bison) to define your grammar and generate the parser (say in C). Such parser can be plugged back to Mathematica either through MathLink or LibraryLink (in the case of C). Its end result would be a string, which, when parsed, would become a valid Mathematica expression. This expression would represent the abstract syntax tree of your parsed code. For example, code like this (new syntax for Fold is introduced here)
"((1|+|{2,3,4,5}))"
could be parsed into something like
"functionCall[fold,{plus,1,{2,3,4,5}}]"
The second component for such a preprocessor would be written in Mathematica, perhaps in a rule-based style, to generate Mathematica code from the AST. The resulting code must be somehow held unevaluated. For the above code, the result might look like
Hold[Fold[Plus,1,{2,3,4,5}]]
It would be best if analogs of tools like Lex(Flex)/Yacc(Bison) were available within Mathematica ( I mean bindings, which would require one to only write code in Mathematica, and generate say C parser from that automatically, plugging it back to the kernel either through MathLink or LibraryLink). I may only hope that they will become available in some future versions. Lacking that, the approach I described would require a lot of low-level work (C, or Java if your prefer). I think it is still doable however. If you can write C (or Java), you may try to do some fairly simple (in terms of the syntax / grammar) language - this may be an interesting project and will give an idea of what it will be like for a more complex one. I'd start with a very basic calculator example, and perhaps change the standard arithmetic operators there to some more weird ones that Mathematica can not parse properly itself, to make it more interesting. To avoid MathLink / LibraryLink complexity at first and just test, you can call the resulting executable from Mathematica with Run, passing the code as one of the command line arguments, and write the result to a temporary file, that you will then import into Mathematica. For the calculator example, the entire thing can be done in a few hours.
Of course, if you only want to abbreviate certain long function names, there is a much simpler alternative - you can use With to do that. Here is a practical example of that - my port of Peter Norvig's spelling corrector, where I cheated in this way to reduce the line count:
Clear[makeCorrector];
makeCorrector[corrector_Symbol, trainingText_String] :=
Module[{model, listOr, keys, words, edits1, train, max, known, knownEdits2},
(* Proxies for some commands - just to play with syntax a bit*)
With[{fn = Function, join = StringJoin, lower = ToLowerCase,
rev = Reverse, smatches = StringCases, seq = Sequence, chars = Characters,
inter = Intersection, dv = DownValues, len = Length, ins = Insert,
flat = Flatten, clr = Clear, rep = ReplacePart, hp = HoldPattern},
(* body *)
listOr = fn[Null, Scan[If[# =!= {}, Return[#]] &, Hold[##]], HoldAll];
keys[hash_] := keys[hash] = Union[Most[dv[hash][[All, 1, 1, 1]]]];
words[text_] := lower[smatches[text, LetterCharacter ..]];
With[{m = model},
train[feats_] := (clr[m]; m[_] = 1; m[#]++ & /# feats; m)];
With[{nwords = train[words[trainingText]],
alphabet = CharacterRange["a", "z"]},
edits1[word_] := With[{c = chars[word]}, join ### Join[
Table[
rep[c, c, #, rev[#]] &#{{i}, {i + 1}}, {i, len[c] - 1}],
Table[Delete[c, i], {i, len[c]}],
flat[Outer[#1[c, ##2] &, {ins[#1, #2, #3 + 1] &, rep},
alphabet, Range[len[c]], 1], 2]]];
max[set_] := Sort[Map[{nwords[#], #} &, set]][[-1, -1]];
known[words_] := inter[words, keys[nwords]]];
knownEdits2[word_] := known[flat[Nest[Map[edits1, #, {-1}] &, word, 2]]];
corrector[word_] := max[listOr[known[{word}], known[edits1[word]],
knownEdits2[word], {word}]];]];
You need some training text with a large number of words as a string to pass as a second argument, and the first argument is the function name for a corrector. Here is the one that Norvig used:
text = Import["http://norvig.com/big.txt", "Text"];
You call it once, say
In[7]:= makeCorrector[correct, text]
And then use it any number of times on some words
In[8]:= correct["coputer"] // Timing
Out[8]= {0.125, "computer"}
You can make your custom With-like control structure, where you hard-code the short names for some long mma names that annoy you the most, and then wrap that around your piece of code ( you'll lose the code highlighting however). Note, that I don't generally advocate this method - I did it just for fun and to reduce the line count a bit. But at least, this is universal in the sense that it will work both interactively and in packages. Can not do infix operators, can not change precedences, etc, etc, but almost zero work.
(my first reply/post.... be gentle)
From my experience, the functionality appears to be a bit of a programming cul-de-sac. The ability to define custom notations seems heavily dependent on using the 'notation palette' to define and clear each custom notation. ('everything is an expression'... well, except for some obscure cases, like Notations, where you have to use a palette.) Bummer.
The Notation package documentation mentions this explicitly, so I can't complain too much.
If you just want to define custom notations in a particular notebook, Notations might be useful to you. On the other hand, if your goal is to implement custom notations in YourOwnPackage.m and distribute them to others, you are likely to encounter issues. (unless you're extremely fluent in Box structures?)
If someone can correct my ignorance on this, you'd make my month!! :)
(I was hoping to use Notations to force MMA to treat subscripted variables as symbols.)
Not a full answer, but just to show a trick I learned here (more related to symbol redefinition than to Notation, I reckon):
Unprotect[Fold];
Fold[f_, x_] :=
Block[{$inMsg = True, result},
result = Fold[f, First#x, Rest#x];
result] /; ! TrueQ[$inMsg];
Protect[Fold];
Fold[f, {a, b, c, d}]
(*
--> f[f[f[a, b], c], d]
*)
Edit
Thanks to #rcollyer for the following (see comments below).
You can switch the definition on or off as you please by using the $inMsg variable:
$inMsg = False;
Fold[f, {a, b, c, d}]
(*
->f[f[f[a,b],c],d]
*)
$inMsg = True;
Fold[f, {a, b, c, d}]
(*
->Fold::argrx: (Fold called with 2 arguments; 3 arguments are expected.
*)
Fold[f, {a, b, c, d}]
That's invaluable while testing

Are there Mathematica packages for presenting proofs/derivations?

When I write out a proof or derivation on paper I frequently make sign errors or drop terms as I move from one step to the next. I'd like to use Mathematica to save myself from these silly mistakes. I don't want Mathematica to solve the expression, I just want to use it carry out and display a series of algebraic manipulations. For a (trivial) example
In[111]:= MultBothSides[Equal[a_, b_], c_] := Equal[c a, c b];
In[112]:= expression = 2 a == a b
Out[112]= 2 a == a b
In[113]:= MultBothSides[expression, 1/a]
Out[113]= 2 == b
Can anyone point me to a package that would support this kind of manipulation?
Edit
Thanks for the input, not quite what I'm looking for though. The symbol manipulation isn't really the problem. I'm really looking for something that will make explicit the algebraic or mathematical justification of each step of a derivation. My goal here is really pedagogical.
Mathematica also provides a number of high-level functions for manipulating algebraic. Among these are Expand, Apart and Together, and Cancel, though there are quite a few more.
Also, for your specific example of applying the same transformation to both sides of an equation (that is, and expression with the head Equal), you can use the Thread function, which works just like your MultBothSides function, but with a great deal more generality.
In[1]:= expression = 2 a == a b
Out[1]:= 2 a == a b
In[2]:= Thread[expression /a, Equal]
Out[2]:= 2 == b
In[3]:= Thread[expression - c, Equal]
Out[3]:= 2 a - c == a b - c
In either of the presented solutions, it should be relatively easy to see what the step entailed. If you want something a little more explicit, you can write your own function like so:
In[4]:= ApplyToBothSides[f_, eq_Equal] := Map[f, eq]
In[5]:= ApplyToBothSides[4 * #&, expression]
Out[5]:= 8 a == 4 a b
It's a generalization of your MultBothSides function that takes advantage of the fact that Map works on expressions with any head, not just head List. If you're trying to communicate with an audience that is unfamiliar with Mathematica, using these sorts of names can help you communicate more clearly. In a related vein, if you want to use replacement rules as suggested by Ira Baxter, it may be helpful to write out Replace or ReplaceAll instead of using the /. syntactic sugar.
In[6]:= ReplaceAll[expression, a -> (x + y)]
Out[6]:= 2 (x + y) == b (x + y)
If you think it would be clearer to have the actual equation, instead of the variable name expression, in your input, and you're using the notebook interface, highlight the word expression with your mouse, call up the contextual menu, and select "Evaluate in Place".
The notebook interface is also a very pleasant environment for doing "literate programming", so you can also explain any steps that are not immediately obvious in words. I believe this is a good practice when writing mathematical proofs regardless of the medium.
I don't think you need a package. What you want to do is to manipulate each formula according to an inference rule. In MMa, you can model inference rules on a formula using transformations. So, if you have a formula f, you can apply an inference rule I by executing (my MMa syntax is 15 years rusty)
f ./ I
to produce the next formula in your sequence.
MMa will of course try to simplify your formulas if they contain standard algebraic operators and terms, such as constant numbers and arithmetic operators. You can prevent MMa from applying its own "inference" rules by enclosing your formula in a Hold[...] form.

Resources