Mathematica not interpreting CenterDot as Times in numerical calculations - wolfram-mathematica

Why doesn't Mathematica show the numerical result of
(0.8\[CenterDot]452\[CenterDot]20+1.5\[CenterDot]4180\[CenterDot]10
-2\[CenterDot]900\[CenterDot]100) / (0.8\[CenterDot]452
+1.5\[CenterDot]4180-1\[CenterDot]2\[CenterDot]900) // N

Just to complete some of the other answers/comments, if you want CenterDot to be interpreted as Times in both input and output by using something like
Unprotect[CenterDot, Times];
CenterDot = Times;
Times /: MakeBoxes[Times[a__], fmt_] :=
With[{cbox = ToBoxes[HoldForm[CenterDot[a]]]},
InterpretationBox[cbox, Times[a]]];
Protect[CenterDot, Times];
Which you can add to your init.m if you want it loaded by default.
This works on both numeric and symbolic expressions, e.g.
In[5]:= 1\[CenterDot]2\[CenterDot]3
Out[5]= 6
In[6]:= a b c
Out[6]= a\[CenterDot]b\[CenterDot]c
You can also make the automatically inserted multiplication symbol between space separated numbers be CenterDot by executing
SetOptions[EvaluationNotebook[],
{AutoMultiplicationSymbol -> True, NumberMultiplier -> "\[CenterDot]"}]
or by selecting Center Dot in the preferences dialog under Appearance > Numbers > Multiplication.
For example:

Just replace \[CenterDot] by a space

Multiplication in Mathematica is written either as a space (Times[a,b] == a b) or as an asterisk (Times[a,b] == a*b). \[CenterDot] is not interpreted as multiplication.

I think Simon's first method can be written more concisely. Please review:
Unprotect[Times];
CenterDot = Times;
Format[a_*b__] := Interpretation[HoldForm[a\[CenterDot]b], a*b];
Second attempt. I believe this works properly with Convert To > StandardForm and editing.
CenterDot = Times;
MakeBoxes[Times[x__], _] := RowBox # Riffle[ToBoxes /# {x}, "\[CenterDot]"]

Related

Specifics of usage and internal work of *Set* functions

I just noticed one undocumented feature of internal work of *Set* functions in Mathematica.
Consider:
In[1]:= a := (Print["!"]; a =.; 5);
a[b] = 2;
DownValues[a]
During evaluation of In[1]:= !
Out[3]= {HoldPattern[a[b]] :> 2}
but
In[4]:= a := (Print["!"]; a =.; 5);
a[1] = 2;
DownValues[a]
During evaluation of In[4]:= !
During evaluation of In[4]:= Set::write: Tag Integer in 5[1] is Protected. >>
Out[6]= {HoldPattern[a[b]] :> 2}
What is the reason for this difference? Why a is evaluated although Set has attribute HoldFirst? For which purposes such behavior is useful?
And note also this case:
In[7]:= a := (Print["!"]; a =.; 5)
a[b] ^= 2
UpValues[b]
a[b]
During evaluation of In[7]:= !
Out[8]= 2
Out[9]= {HoldPattern[5[b]] :> 2}
Out[10]= 2
As you see, we get the working definition for 5[b] avoiding Protected attribute of the tag Integer which causes error in usual cases:
In[13]:= 5[b] = 1
During evaluation of In[13]:= Set::write: Tag Integer in 5[b] is Protected. >>
Out[13]= 1
The other way to avoid this error is to use TagSet*:
In[15]:= b /: 5[b] = 1
UpValues[b]
Out[15]= 1
Out[16]= {HoldPattern[5[b]] :> 1}
Why are these features?
Regarding my question why we can write a := (a =.; 5); a[b] = 2 while cannot a := (a =.; 5); a[1] = 2. In really in Mathematica 5 we cannot write a := (a =.; 5); a[b] = 2 too:
In[1]:=
a:=(a=.;5);a[b]=2
From In[1]:= Set::write: Tag Integer in 5[b] is Protected. More...
Out[1]=
2
(The above is copied from Mathematica 5.2)
We can see what happens internally in new versions of Mathematica when we evaluate a := (a =.; 5); a[b] = 2:
In[1]:= a:=(a=.;5);
Trace[a[b]=2,TraceOriginal->True]
Out[2]= {a[b]=2,{Set},{2},a[b]=2,{With[{JLink`Private`obj$=a},RuleCondition[$ConditionHold[$ConditionHold[JLink`CallJava`Private`setField[JLink`Private`obj$[b],2]]],Head[JLink`Private`obj$]===Symbol&&StringMatchQ[Context[JLink`Private`obj$],JLink`Objects`*]]],{With},With[{JLink`Private`obj$=a},RuleCondition[$ConditionHold[$ConditionHold[JLink`CallJava`Private`setField[JLink`Private`obj$[b],2]]],Head[JLink`Private`obj$]===Symbol&&StringMatchQ[Context[JLink`Private`obj$],JLink`Objects`*]]],{a,a=.;5,{CompoundExpression},a=.;5,{a=.,{Unset},a=.,Null},{5},5},RuleCondition[$ConditionHold[$ConditionHold[JLink`CallJava`Private`setField[5[b],2]]],Head[5]===Symbol&&StringMatchQ[Context[5],JLink`Objects`*]],{RuleCondition},{Head[5]===Symbol&&StringMatchQ[Context[5],JLink`Objects`*],{And},Head[5]===Symbol&&StringMatchQ[Context[5],JLink`Objects`*],{Head[5]===Symbol,{SameQ},{Head[5],{Head},{5},Head[5],Integer},{Symbol},Integer===Symbol,False},False},RuleCondition[$ConditionHold[$ConditionHold[JLink`CallJava`Private`setField[5[b],2]]],False],Fail},a[b]=2,{a[b],{a},{b},a[b]},2}
I was very surprised to see calls to Java in such a pure language-related operation as assigning a value to a variable. Is it reasonable to use Java for such operations at all?
Todd Gayley (Wolfram Research) has explained this behavior:
At the start, let me point out that in
Mathematica 8, J/Link no longer
overloads Set. An internal kernel
mechanism was created that, among
other things, allows J/Link to avoid
the need for special, er, "tricks"
with Set.
J/Link has overloaded Set from the
very beginning, almost twelve years
ago. This allows it support this
syntax for assigning a value to a Java
field:
javaObject#field = value
The overloaded definition of Set
causes a slowdown in assignments of
the form
_Symbol[_Symbol] = value
Of course, assignment is a fast
operation, so the slowdown is small in
real terms. Only highly specialized
types of programs are likely to be
significantly affected.
The Set overload does not cause a
call to Java on assignments that do
not involve Java objects (this would
be very costly). This can be verified
with a simple use of TracePrint on
your a[b]=c.
It does, as you note, make a slight
change in the behavior of assignments
that match _Symbol[_Symbol] = value.
Specifically, in f[_Symbol] = value, f
gets evaluated twice. This can cause
problems for code with the following
(highly unusual) form:
f := SomeProgramWithSideEffects[]
f[x] = 42
I cannot recall ever seeing "real"
code like this, or seeing a problem
reported by a user.
This is all moot now in 8.0.
Taking the case of UpSet first, this is expected behavior. One can write:
5[b] ^= 1
The assignment is made to b not the Integer 5.
Regarding Set and SetDelayed, while these have Hold attributes, they still internally evaluate expressions. This allows things such as:
p = n : (_List | _Integer | All);
f[p] := g[n]
Test:
f[25]
f[{0.1, 0.2, 0.3}]
f[All]
g[25]
g[{0.1, 0.2, 0.3}]
g[All]
One can see that heads area also evaluated. This is useful at least for UpSet:
p2 = head : (ff | gg);
p2[x] ^:= Print["Echo ", head];
ff[x]
gg[x]
Echo ff
Echo gg
It is easy to see that it happens also with Set, but less clear to me how this would be useful:
j = k;
j[5] = 3;
DownValues[k]
(* Out= {HoldPattern[k[5]] :> 3} *)
My analysis of the first part of your question was wrong. I cannot at the moment see why a[b] = 2 is accepted and a[1] = 2 is not. Perhaps at some stage of assignment the second one appears as 5[1] = 2 and a pattern check sets off an error because there are no Symbols on the LHS.
The behavour you show appears to be a bug in 7.0.1 (and possibly earlier) that was fixed in Mathematica 8. In Mathematica 8, both of your original a[b] = 2 and a[1] = 2 examples give the Set::write ... is protected error.
The problem appears to stem from the JLink-related down-value of Set that you identified. That rule implements the JLink syntax used to assign a value to the field of a Java object, e.g. object#field = value.
Set in Mathematica 8 does not have that definition. We can forcibly re-add a similar definition, thus:
Unprotect[Set]
HoldPattern[sym_Symbol[arg_Symbol]=val_] :=
With[{obj=sym}
, setField[obj[arg], val] /; Head[obj] === Symbol && StringMatchQ[Context[obj],"Something`*"]
]
After installing this definition in Mathematica 8, it now exhibits the same inconsistent behaviour as in Mathematica 7.
I presume that JLink object field assignment is now accomplished through some other means. The problematic rule looks like it potentially adds costly Head and StringMatchQ tests to every evaluation of the form a[b] = .... Good riddance?

How to store punch of equations / constants to solve for any element equation or numerical value

Lets say, that problems are fairly simple - something, that pre-degree theoretical physics student would solve. And student does the hardest part of the task - functional reading: parsing linguistically free form text, to get input and output variables and input variable values.
For example: a problem about kinematic equations, where there are variables {a,d,t,va,vf} and few functions that describe, how thy are dependent of each-other. So using skills acquired in playing fitting blocks where thy fit, you play with the equations to get the output variable you where looking for.
In any case, there are exactly 2 possible outputs you might want and thy are (with working example):
1) Equation for that variable
Physics[have_, find_] := Solve[Flatten[{
d == vf * t - (a * t^2) /2, (* etc. *)
have }], find]
Physics[True, {d}]
{{d -> (1/2)*(2*t*vf - a*t^2)}}
2) Exact or general numerical value for that variable
Physics[have_, find_] := Solve[Flatten[{
d == vf * t - (a * t^2) /2, (* etc. *)
have }], find]
Physics[{t == 9.7, vf == -104.98, a == -9.8}, {d}]
{{d->-557.265}}
I am not sure, that I am approaching the problem correctly.
I think that I would probably prefer an approach like
In[1]:= Physics[find_, have_:{}] := Solve[
{d == vf*t - (a*t^2)/2 (* , etc *)} /. have, find]
In[2]:= Physics[d]
Out[2]= {{d -> 1/2 (-a t^2 + 2 t vf)}}
In[2]:= Physics[d, {t -> 9.7, vf -> -104.98, a -> -9.8}]
Out[2]= {{d -> -557.265}}
Where the have variables are given as a list of replacement rules.
As an aside, in these types of physics problems, a nice thing to do is define your physical constants like
N[g] = -9.8;
which produces a NValues for g. Then
N[tf] = 9.7;N[vf] = -104.98;
Physics[d, {t -> tf, vf -> vf, a -> g}]
%//N
produces
{{d->1/2 (-g tf^2+2 tf vf)}}
{{d->-557.265}}
Let me show some advanges of Simon's approach:
You are at least approaching this problem reasonably. I see a fine general purpose function and I see you're getting results, which is what matters primarily. There is no 'correct' solution, since there might be a large range of acceptable solutions. In some scenario's some solutions may be preferred over others, for instance because of performance, while that might be the other way around in other scenarios.
The only slight problem I have with your example is the dubious parametername 'have'.
Why do you think this would be a wrong approach?

Noncommutative Multiplication and Negative coeffcients at the Beginning of an Expression in Mathematica

With the help of some very gracious stackoverflow contributors in this post, I have the following new definition for NonCommutativeMultiply (**) in Mathematica:
Unprotect[NonCommutativeMultiply];
ClearAll[NonCommutativeMultiply]
NonCommutativeMultiply[] := 1
NonCommutativeMultiply[___, 0, ___] := 0
NonCommutativeMultiply[a___, 1, b___] := a ** b
NonCommutativeMultiply[a___, i_Integer, b___] := i*a ** b
NonCommutativeMultiply[a_] := a
c___ ** Subscript[a_, i_] ** Subscript[b_, j_] ** d___ /; i > j :=
c ** Subscript[b, j] ** Subscript[a, i] ** d
SetAttributes[NonCommutativeMultiply, {OneIdentity, Flat}]
Protect[NonCommutativeMultiply];
This multiplication is great, however, it does not deal with negative values at the beginning of an expression, i.e.,
a**b**c + (-q)**c**a
should simplify to
a**b**c - q**c**a
and it will not.
In my multiplication, the variable q (and any integer scaler) is commutative; I am still trying to write a SetCommutative function, without success. I am not in desperate need of SetCommutative, it would just be nice.
It would also be helpful if I were able to pull all of the q's to the beginning of each expression, i.e.,:
a**b**c + a**b**q**c**a
should simplify to:
a**b**c + q**a**b**c**a
and similarly, combining these two issues:
a**b**c + a**c**(-q)**b
should simplify to:
a**b**c - q**a**c**b
At the current time, I would like to figure out how to deal with these negative variables at the beginning of an expression and how to pull the q's and (-q)'s to the front as above. I have tried to deal with the two issues mentioned here using ReplaceRepeated (\\.), but so far I have had no success.
All ideas are welcome, thanks...
The key to doing this is to realize that Mathematica represents a-b as a+((-1)*b), as you can see from
In[1]= FullForm[a-b]
Out[2]= Plus[a,Times[-1,b]]
For the first part of your question, all you have to do is add this rule:
NonCommutativeMultiply[Times[-1, a_], b__] := - a ** b
or you can even catch the sign from any position:
NonCommutativeMultiply[a___, Times[-1, b_], c___] := - a ** b ** c
Update -- part 2. The general problem with getting scalars to front is that the pattern _Integer in your current rule will only spot things that are manifestly integers. It wont even spot that q is an integer in a construction like Assuming[{Element[q, Integers]}, a**q**b].
To achieve this, you need to examine assumptions, a process that is probably to expensive to be put in the global transformation table. Instead I would write a transformation function that I could apply manually (and maybe remove the current rule form the global table). Something like this might work:
NCMScalarReduce[e_] := e //. {
NonCommutativeMultiply[a___, i_ /; Simplify#Element[i, Reals],b___]
:> i a ** b
}
The rule used above uses Simplify to explicitly query assumptions, which you can set globally by assigning to $Assumptions or locally by using Assuming:
Assuming[{q \[Element] Reals},
NCMScalarReduce[c ** (-q) ** c]]
returns -q c**c.
HTH
Just a quick answer that repeats some of the comments from the previous question.
You can remove a couple of the definitions and solve all of the parts of this question using the rule that acts on Times[i,c] where i is commutative and c has the default of Sequence[]
Unprotect[NonCommutativeMultiply];
ClearAll[NonCommutativeMultiply]
NonCommutativeMultiply[] := 1
NonCommutativeMultiply[a___, (i:(_Integer|q))(c_:Sequence[]), b___] := i a**Switch[c, 1, Unevaluated[Sequence[]], _, c]**b
NonCommutativeMultiply[a_] := a
c___**Subscript[a_, i_]**Subscript[b_, j_] ** d___ /; i > j := c**Subscript[b, j]**Subscript[a, i]**d
SetAttributes[NonCommutativeMultiply, {OneIdentity, Flat}]
Protect[NonCommutativeMultiply];
This then works as expected
In[]:= a**b**q**(-c)**3**(2 a)**q
Out[]= -6 q^2 a**b**c**a
Note that you can generalize (_Integer|q) to work on more general commutative objects.

Problem performing a substitution in a multiple derivative

I have a basic problem in Mathematica which has puzzled me for a while. I want to take the m'th derivative of x*Exp[t*x], then evaluate this at x=0. But the following does not work correct. Please share your thoughts.
D[x*Exp[t*x], {x, m}] /. x -> 0
Also what does the error mean
General::ivar: 0 is not a valid variable.
Edit: my previous example (D[Exp[t*x], {x, m}] /. x -> 0) was trivial. So I made it harder. :)
My question is: how to force it to do the derivative evaluation first, then do substitution.
As pointed out by others, (in general) Mathematica does not know how to take the derivative an arbitrary number of times, even if you specify that number is a positive integer.
This means that the D[expr,{x,m}] command remains unevaluated and then when you set x->0, it's now trying to take the derivative with respect to a constant, which yields the error message.
In general, what you want is the m'th derivative of the function evaluated at zero.
This can be written as
Derivative[m][Function[x,x Exp[t x]]][0]
or
Derivative[m][# Exp[t #]&][0]
You then get the table of coefficients
In[2]:= Table[%, {m, 1, 10}]
Out[2]= {1, 2 t, 3 t^2, 4 t^3, 5 t^4, 6 t^5, 7 t^6, 8 t^7, 9 t^8, 10 t^9}
But a little more thought shows that you really just want the m'th term in the series, so SeriesCoefficient does what you want:
In[3]:= SeriesCoefficient[x*Exp[t*x], {x, 0, m}]
Out[3]= Piecewise[{{t^(-1 + m)/(-1 + m)!, m >= 1}}, 0]
The final output is the general form of the m'th derivative. The PieceWise is not really necessary, since the expression actually holds for all non-negative integers.
Thanks to your update, it's clear what's happening here. Mathematica doesn't actually calculate the derivative; you then replace x with 0, and it ends up looking at this:
D[Exp[t*0],{0,m}]
which obviously is going to run into problems, since 0 isn't a variable.
I'll assume that you want the mth partial derivative of that function w.r.t. x. The t variable suggests that it might be a second independent variable.
It's easy enough to do without Mathematica: D[Exp[t*x], {x, m}] = t^m Exp[t*x]
And if you evaluate the limit as x approaches zero, you get t^m, since lim(Exp[t*x]) = 1. Right?
Update: Let's try it for x*exp(t*x)
the mth partial derivative w.r.t. x is easily had from Wolfram Alpha:
t^(m-1)*exp(t*x)(t*x + m)
So if x = 0 you get m*t^(m-1).
Q.E.D.
Let's see what is happening with a little more detail:
When you write:
D[Sin[x], {x, 1}]
you get an expression in with x in it
Cos[x]
That is because the x in the {x,1} part matches the x in the Sin[x] part, and so Mma understands that you want to make the derivative for that symbol.
But this x, does NOT act as a Block variable for that statement, isolating its meaning from any other x you have in your program, so it enables the chain rule. For example:
In[85]:= z=x^2;
D[Sin[z],{x,1}]
Out[86]= 2 x Cos[x^2]
See? That's perfect! But there is a price.
The price is that the symbols inside the derivative get evaluated as the derivative is taken, and that is spoiling your code.
Of course there are a lot of tricks to get around this. Some have already been mentioned. From my point of view, one clear way to undertand what is happening is:
f[x_] := x*Exp[t*x];
g[y_, m_] := D[f[x], {x, m}] /. x -> y;
{g[p, 2], g[0, 1]}
Out:
{2 E^(p t) t + E^(p t) p t^2, 1}
HTH!

Passing parameters stored in a list to expression

How can I pass values to a given expression with several variables? The values for these variables are placed in a list that needs to be passed into the expression.
Your revised question is straightforward, simply
f ## {a,b,c,...} == f[a,b,c,...]
where ## is shorthand for Apply. Internally, {a,b,c} is List[a,b,c] (which you can see by using FullForm on any expression), and Apply just replaces the Head, List, with a new Head, f, changing the function. The operation of Apply is not limited to lists, in general
f ## g[a,b] == f[a,b]
Also, look at Sequence which does
f[Sequence[a,b]] == f[a,b]
So, we could do this instead
f[ Sequence ## {a,b}] == f[a,b]
which while pedantic seeming can be very useful.
Edit: Apply has an optional 2nd argument that specifies a level, i.e.
Apply[f, {{a,b},{c,d}}, {1}] == {f[a,b], f[c,d]}
Note: the shorthand for Apply[fcn, expr,{1}] is ###, as discussed here, but to specify any other level description you need to use the full function form.
A couple other ways...
Use rule replacement
f /. Thread[{a,b} -> l]
(where Thread[{a,b} -> l] will evaluate into {a->1, b->2})
Use a pure function
Function[{a,b}, Evaluate[f]] ## l
(where ## is a form of Apply[] and Evaluate[f] is used to turn the function into Function[{a,b}, a^2+b^2])
For example, for two elements
f[l_List]:=l[[1]]^2+l[[2]]^2
for any number of elements
g[l_List] := l.l
or
h[l_List]:= Norm[l]^2
So:
Print[{f[{a, b}], g[{a, b}], h[{a, b}]}]
{a^2 + b^2, a^2 + b^2, Abs[a]^2 + Abs[b]^2}
Two more, just for fun:
i[l_List] := Total#Table[j^2, {j, l}]
j[l_List] := SquaredEuclideanDistance[l, ConstantArray[0, Length[l]]
Edit
Regarding your definition
f[{__}] = a ^ 2 + b ^ 2;
It has a few problems:
1) You are defining a constant, because the a,b are not parameters.
2) You are defining a function with Set, Instead of SetDelayed, so the evaluation is done immediately. Just try for example
s[l_List] = Total[l]
vs. the right way:
s[l_List] := Total[l]
which remains unevaluated until you use it.
3) You are using a pattern without a name {__} so you can't use it in the right side of the expression. The right way could be:
f[{a_,b_}]:= a^2+b^2;

Resources