A34 ==== Try to turn off lighting (in options: Lighting->False ).I presume you are using graphics primitives for your surfaces and have readthe help file forSurfaceColor[ frontcolor, backcolor ]Then I think it should work.Nicholas> I need to color the surface of a regular polyhedron (an icosahedron,> specifically) according to a relatively simple function of the spatial> coordinates of the surface. I easily got a nice icosahedron of the> appropriate size, but thus far I have been unable to resolve the> coloring issue.>> Any advice is appreciated.>> Francis>Reply-To: kuska@informatik.uni-leipzig.de ==== a) you can manual return the symbol $Failed your function should have the ReturnType Manual this is typical sufficient when there are not more things that can go wrongb) define a message with Evaluate :Evaluate: CFunctions::nomem=foo is out of memory and use MLEvaluateString(stdlink,Message[CFunctions::nomem];); and clean the link to discard the resultc) you can return always a list {errorCode,functionResult} to Mathematica and the Mathematica function generate the messages due to the errorCode or return the functionResult Jens > G'day all,> How do I return errors to Mathematica from a MathLink program?> For e.g.> ...> ptr = malloc( HUGE_VAL );> if (ptr == NULL) {> // How do I return an error value to mathematica here?> }> Yas ==== =I've made two small rutines for sampling (bootstrap statistics)They are working , but at least ÔSampleNoReplace' is rather slowI was wondering if any of you know of a faster way to do thisSampelReplace[data_List:{0, 1}, n_:1] := Module[{}, data[[Table[Random[Integer, {1, Length@data} ], {n}]]]]SampelNoReplace[data_List, n_] := Module[{idx, len, res, d, hi, i}, d = data; res = {}; len = hi = Length@d; For[i = 1, i <= n && i <= len, i++, idx = Random[Integer, {1, hi--} ]; AppendTo[res, d[[idx]]]; d = Drop[d, {idx}]; ]; res ] ==== =I am trying to evalute a function which looks like this. This is ananalogous problem not the actual problem.test[x_] := p /. FindRoot[Sin[p] == x, {p, 1}][[1]]data[x_] := D[test[x], x]Plot[data[x], {x, 0, 1}]Now, when trying to evaluate the derivative mathematica replaces both thex's with the number at which it is trying to calculate the datapoint. Thisgives an error of Ôxxxx is not a valid variable'. Replacing D[test[x]]with test'[x] doesn't help either though it results in a different set oferrors. Is there any of way of getting around this problem?Farhat ==== =>I have understood that parentheses ( ) are displayed as HL in>exported postscript due to the fact that postscript viewers are not>accessing the Mathematica Fonts that encode ( ). I thought I>could avoid this problem by specifying a different font, in this>case Courier for the parentheses. This didn't work. Is there a>related idea that will work?>>parenGraphic = Show[Graphics[{ Text[ StyleForm[(, FontFamily ->>Courier, FontWeight -> Plain] , {0, 0}]>}]];>>Export[parenGraphic.eps, parenGraphic]>Todd Will UW-LaCrosseTry this instead...parenGraphic = Show[Graphics[{Text[ StyleForm[(, PrivateFontOptions -> {OperatorSubstitution -> False}], {0, 0}]}]];(and actually you don't need to make a separate graphic out of this, you can just throw this in the TextStyle option for the whole graphic)You can also set the OperatorSubstitution option to False at the global level using the Option Inspector, which would affect all uses of parens, brackets, etc., in Mathematica...in input and output cells as well as graphics. Of course, you'll still need to include the Mathematica fonts for those characters which have no corresponding characters in the regular fonts, like Greek letters and radicals.Sincerely,John Fultzjfultz@wolfram.comUser Interface GroupWolfram Research, Inc. ==== =Layering, that is slightly separating the various contour polygons, seems tosolve the problem of overlapping 3D polygons, and triangulation seems tosolve the problem of concave 3D polygons.David Parkdjmp@earthlink.nethttp://home.earthlink.net/~djmp/ Ted Ersek ==== =>How do you remove the In[] and Out[] lines so they don't appear when you>print?>>Brian (averso@yahoo.com)In the option inspector:Set Show option values for to notebook.Then set Cell Options|Cell Labels|ShowCellLabel->False---------------------------------- ----------------------------Omega ConsultingThe final answer to your Mathematica needsSpend less time searching and more time finding.http://www.wz.com/internet/Mathematica.htmlReply-To: ==== =Here's a method that's not blindingly fast, but still interesting:a = {0.5, 0.25, 0.3}; b = {0.125, 0.35, 0.03}; {tmin, tmax} = {0, 2*Pi}; f[t_] := a . {Sin[t], Sin[2*t], Sin[3*t]}; g[t_] := b . {Cos[t], Cos[2*t], Cos[3*t]}h[t_, {x_, y_}] = (f[t] - x)^2 + (g[t] - y)^2; j[t_, {x_, y_}] = Simplify[ D[h[t, {x, y}], t]]; i[t_, {x_, y_}] := guess=2*t - guess /. FindRoot[h[t,{x, y}], {t,guess},Jacobian -> {{j[t, {x, y}]}}]Timing[plot = ParametricPlot[{f[t], g[t]}, {t, tmin, tmax}]; list = Cases[plot, {x_, y_}, Infinity]; guess = tmin; tvals = (i[t, #1] & ) /@ list; ]ListPlot[tvals]{0.281 Second, Null}This is slightly faster, though probably not worth the extra effort:nextGuess := guess.{1, -3, 3} (* quadratic extrapolation from previousguesses *)i[t_, {x_, y_}] := (guess = Join[Rest@guess, {t}] /. FindRoot[h[t, {x, y}], {t, nextGuess}, Jacobian -> {{j[t, {x,y}]}}])Timing[plot = ParametricPlot[{f[t], g[t]}, {t, tmin, tmax}]; list = Cases[plot, {x_, y_}, Infinity]; guess = tmin{1, 1, 1}; tvals2 = Last@i[t, #] & /@ list; ]{0.266 Second, Null}DrBob-----Original Message----->values used by ParametricPlot in plotting a curve,>e.g. if ParametricPlot used points corresponding to>parameter values 2, 4, 6, etc... I need a way to get>the list {2, 4, 6, ...}.>>One solution I know is this:>>list={};>ParametricPlot[(AppendTo[list,t]; {f[t]>g[t]}),{t,tmin,tmax}];>>The problem with this is that I get an error that>ParametricPlot cannot compile the function, and that>the plotting time is considerably slowed down.>especially if I have a high PlotPoints setting.>>Any ideas?>> Jan Mangaldan (~_~)Jan,please observe:In[1]:= a = {0.5, 0.25, 0.3}; b = {0.125, 0.35, 0.03}; In[2]:=f[t_] := a . {Sin[t], Sin[2*t], Sin[3*t]}; g[t_] := b . {Cos[t], Cos[2*t], Cos[3*t]}In[4]:= {tmin, tmax} = {0, 2*Pi}; In[5]:= list = {}; s = {f[t], g[t]}; Timing[ParametricPlot[list = {list, t}; s, {t, tmin, tmax}]]ParametricPlot::ppcom: Function !(((list = (({list, t}))));s) cannot be compiled; plotting will proceed with the uncompiled function.Out[6]= {0.231 Second, - Graphics -}In[7]:= tt = Flatten[list]; Length[tt] ss = -Apply[Subtract, Partition[tt, 2, 1], {1}]; Out[8]= 271In[10]:= ListPlot[tt]In[11]:= ListPlot[ss, PlotJoined -> True, PlotRange -> All]In[12]:= Timing[ParametricPlot[{f[t], g[t]}, {t, tmin, tmax}]]Out[12]= {0.25 Second, - Graphics -}You see the uncompiled version, including registering of the t-samplesisfaster than the compiled version?In[13]:=Timing[ParametricPlot[Evaluate[{f[t], g[t]}], {t, tmin, tmax}]]Out[13]= {0.04 Second, - Graphics -}In[14]:=list = {}; s = Compile[t,{f[t], g[t]}]; Timing[ParametricPlot[list = {list, t}; s[t], {t, tmin, tmax}];]Out[15]= {0.32 Second, Null}In[16]:=list = {}; s = Compile[t,Evaluate[{f[t], g[t]}]]; Timing[ParametricPlot[list = {list, t}; s[t], {t, tmin, tmax}];]Out[17]= {0.1 Second, Null}--Hartmut Wolf ==== =I've made two small rutines for sampling (bootstrap statistics)They are working , but at least ÔSampleNoReplace' is rather slowI was wondering if any of you know of a faster way to do thisSampelReplace[data_List:{0, 1}, n_:1] := Module[{}, data[[Table[Random[Integer, {1, Length@data} ], {n}]]]]SampelNoReplace[data_List, n_] := Module[{idx, len, res, d, hi, i}, d = data; res = {}; len = hi = Length@d; For[i = 1, i <= n && i <= len, i++, idx = Random[Integer, {1, hi--} ]; AppendTo[res, d[[idx]]]; d = Drop[d, {idx}]; ]; res ] ==== =>-----Original Message----->Sent: Thursday, October 24, 2002 8:55 AM>To: mathgroup@smc.vnet.net>I've made two small rutines for sampling (bootstrap statistics)>They are working , but at least ÔSampleNoReplace' is rather slow>I was wondering if any of you know of a faster way to do this>>SampelReplace[data_List:{0, 1}, n_:1] := > Module[{}, data[[Table[Random[Integer, {1, Length@data} ], {n}]]]]>>SampelNoReplace[data_List, n_] := Module[{idx, len, res, d, hi, i},> d = data;> res = {};> len = hi = Length@d;> > For[i = 1, i <= n && i <= len, i++,> idx = Random[Integer, {1, hi--} ];> AppendTo[res, d[[idx]]];> d = Drop[d, {idx}];> ];> res> ]>SÀren,try<< DiscreteMath`Combinatorica`SampelNoReplace[data_List, n_] := With[{len = Length[data]}, data[[Take[RandomPermutation[len], Min[len, n]] ]] ]Most probably this is good enough, if n is *very* small compared to Lengthof data (and data is *very* *very* large), then other strategies areconceivable, e.g.SampelNoReplace[data_List, n_] /; n <= Length[data] :=data[[Take[ NestWhile[ UnorderedUnion[ Join[Table[ Random[Integer, {1, Length[data]}], {2 n}], #]] &, {}, Length[#] < n &], n] ]]where UnorderedUnion is a stroke of genius from Karl Woll, searchable in thearchive:UnorderedUnion[li_List] := Block[{i, Sequence}, i[n_] := (i[n] = Sequence[]; n); i /@ li](You might like to tune the excess of probing over n ( a factor 2 here,might be made much less), such that NestWhile most probably won't loop.)Another, somewhat related idea would be:SampelNoReplace[data_List, n_] :=data[[Module[{hit, i, len = Length[data]}, hit[i_] := False; Table[(While[hit[i = Random[Integer, {1, len}]]]; hit[i] = True; i), {Min[n, len]}]] ]]This one however is no good if the the data are very large and n comes nearto the length, but then the first proposal is appropriate. With varyingrequirements make conditional definitions.--Hartmut Wolf ==== =My deepest apologies, Jens. You're right---the function I gave only plots Poincare *time* sections. However, it *does work* for autonomous (2x2) systems; it just doesn't do anything interesting. Selwyn> that work only for non-autonomos systems but the original > message speak about Hamiltonian systems. For a> autonomous system your function does not work at all, because> you have to find the intersection points of the solution> with a plane in phase space.> Jens>>Not entirely sure what you're asking for, but here's a simple routine>>that plots a Poincare section for a pair of ODEs with vector field (f,g):>>PoincareSection[{f_,g_}, {t_,t0_,tmax_,dt_}, {x_,x0_}, {y_,y0_}] :=>> Module[{xsoln, ysoln},>> {xsoln, ysoln} = {x, y} /. First@>> NDSolve[{x'[t] == (f /. {x -> x[t], y -> y[t]}),>> y'[t] ==(g /. {x -> x[t], y -> y[t]}),>> x[0]==x0, y[0]==y0}, {x, y},>> {t, t0, tmax}, MaxSteps -> Infinity];>> ListPlot[Table[{xsoln[t], ysoln[t]}, {t, t0, tmax, dt}]]]>>And this is the classic example with Duffing's equation:>>PoincareSection[{y, x - x^3 - 0.2y + 0.3Cos[t]},{t,0,3000,2Pi},>> {x, -1}, {y, 1}]>>--->>Selwyn Hollis>>>Do you have some package that helps me vizualize subj. when i start from>________________________________________________________ __________ ckkm>________________________________________________________ __________>>>>>>> Reply-To: kuska@informatik.uni-leipzig.de ==== =that work only for non-autonomos systems but the original message speak about Hamiltonian systems. For aautonomous system your function does not work at all, becauseyou have to find the intersection points of the solutionwith a plane in phase space. Jens> Not entirely sure what you're asking for, but here's a simple routine> that plots a Poincare section for a pair of ODEs with vector field (f,g):> PoincareSection[{f_,g_}, {t_,t0_,tmax_,dt_}, {x_,x0_}, {y_,y0_}] :=> Module[{xsoln, ysoln},> {xsoln, ysoln} = {x, y} /. First@> NDSolve[{x'[t] == (f /. {x -> x[t], y -> y[t]}),> y'[t] ==(g /. {x -> x[t], y -> y[t]}),> x[0]==x0, y[0]==y0}, {x, y},> {t, t0, tmax}, MaxSteps -> Infinity];> ListPlot[Table[{xsoln[t], ysoln[t]}, {t, t0, tmax, dt}]]]> And this is the classic example with Duffing's equation:> PoincareSection[{y, x - x^3 - 0.2y + 0.3Cos[t]},{t,0,3000,2Pi},> {x, -1}, {y, 1}]> ---> Selwyn Hollis> Do you have some package that helps me vizualize subj. when i start from> _____________________________________________________________ _____ ckkm> _____________________________________________________________ _____>> ==== =So ArcTan can take two arguments... what a concept! Here's a cleaner version of my previous post.<< Graphics`PlotField`;Off[ArcTan::indet];rot[q_] := {{Cos[q], -Sin[q]}, {Sin[q], Cos[q]}};PlotPolarVectorField[{f_, g_}, {r_, q_}, {x_, x1_, x2_}, {y_, y1_, y2_}, opts___Rule] :=PlotVectorField[rot[q].{f, g} /. {r -> Sqrt[x^2 + y^2], q -> ArcTan[x, y]}, {x, x1, x2}, {y, y1, y2}, opts];PlotPolarVectorField[{r, Sin[q]}, {r, q}, {x, -1, 1}, {y, -1, 1}]<< Graphics`PlotField3D`;PlotCylindricalVectorField[{f_, g_, h_}, {r_, q_, z_}, {x_, x1_, x2_}, {y_, y1_, y2_}, {z_, z1_, z2_}, opts___Rule] := PlotVectorField3D[Append[rot[q].{f, g}, h] /. {r -> Sqrt[x^2 + y^2], q -> ArcTan[x, y]}, {x, x1, x2}, {y, y1, y2}, {z, z1, z2}, opts];PlotCylindricalVectorField[{0, 1, 0}, {r, q, z}, {x, -1, 1}, {y, -1, 1}, {z, 0, 1}]----Selwyn Hollis> Here's a way of plotting a polar vector field {f(r,q], g[r,q]} (q is the > angle) by means of PlotField:> < angle[x_, y_] := Which[x<0, ArcTan[y/x]+Pi, x*y<0, ArcTan[y/x]+2*Pi, > x!=0, ArcTan[y/x], x==0, Sign[y]*(Pi/2)];> Off[Power::infy, Infinity::indet];> PlotPolarVectorField[{f_,g_}, {r_,q_}, {x_,x1_,x2_}, {y_,y1_,y2_}, > opts___Rule] :=> PlotVectorField[{f*Cos[q] - g*Sin[q], f*Sin[q] + g*Cos[q]} /.> {r -> Sqrt[x^2 + y^2], q -> angle[x, y]},> {x, x1, x2}, {y, y1, y2}, opts];> (* Example *)> PlotPolarVectorField[{r, Sin[q]}, {r, q}, {x, -1, 1}, {y, -1, 1}]> This uses the same idea to plot a 3D vector field in cylindrical > coordinates:> < PlotCylindricalVectorField[{f_,g_,h_}, {r_,q_,z_}, {x_,x1_,x2_},> {y_, y1_, y2_}, {z_, z1_, z2_}, opts___Rule] :=> PlotVectorField3D[{f*Cos[q] - g*Sin[q], f*Sin[q] + g*Cos[q], h} /.> {r -> Sqrt[x^2 + y^2], q -> angle[x, y]},> {x, x1, x2}, {y, y1, y2}, {z, z1, z2}, opts];> (* Example *)> PlotCylindricalVectorField[{0,1,0},{r,q,z},{x,-1,1},{y,-1,1},{ z,0, 1}]> ----> Selwyn Hollis>>Someone known if is possible to create a 3DPlot Vector>>Field using Cylindrical coordinates.>>Using Calculus`VectorAnalysis` Add-on, I can set>>coordinates but Graphics`PlotField3D` seems not using>>the coordinates setted, it works in Cartesian system>>in any case.>>Any idea?>>Stefano Fricano.>>___________________________________________________ ___________________>>Mio Yahoo!: personalizza Yahoo! come piace a te >>> ==== =Here's a way of plotting a polar vector field {f(r,q], g[r,q]} (q is the angle) by means of PlotField:< Sqrt[x^2 + y^2], q -> angle[x, y]}, {x, x1, x2}, {y, y1, y2}, opts];(* Example *)PlotPolarVectorField[{r, Sin[q]}, {r, q}, {x, -1, 1}, {y, -1, 1}]This uses the same idea to plot a 3D vector field in cylindrical coordinates:< Sqrt[x^2 + y^2], q -> angle[x, y]}, {x, x1, x2}, {y, y1, y2}, {z, z1, z2}, opts];(* Example *)PlotCylindricalVectorField[{0,1,0},{r,q,z},{x,-1,1},{y,-1,1 },{z,0, 1}]----Selwyn Hollis> Someone known if is possible to create a 3DPlot Vector> Field using Cylindrical coordinates.> Using Calculus`VectorAnalysis` Add-on, I can set> coordinates but Graphics`PlotField3D` seems not using> the coordinates setted, it works in Cartesian system> in any case.> Any idea?> Stefano Fricano.> _____________________________________________________________ _________> Mio Yahoo!: personalizza Yahoo! come piace a te > Reply-To: ==== =Try this:Off[Solve::ifun]test[x_] := p /. First@Solve[Sin[p] == x, p]data[x_] := D[test[y], y] /. y -> xPlot[data[x], {x, 0, 1}]In order to differentiate test[x] at x, it's necessary for x to be asymbol, but when data[x] is evaluated x has a value, so D[test[x],x]can't work. Hence we take the derivative at y and then replace y withx. Since y has no value, FindRoot can't do the job, since it has tohave numerics to work with (other than p). If you have a problem Solvecan't handle, then you can't differentiate it symbolically; you'll haveto choose a small delta and do everything numerically, something likethis:delta = 0.00001; start = 0.; test[x_] := start = p /. FindRoot[Sin[p] == x, {p, start}, AccuracyGoal-> 8]data[x_] := (test[x + delta] - test[x - delta])/(2*delta)Plot[data[x], {x, 0, 1 - delta}]For x very close to 1, the AccuracyGoal has to be increased; the Plotstabilizes when the goal is increased to 10 or more.For your REAL problem, of course, things may be different.Returning to the example, it's possible to compute the derivative of pwithout solving for p:Sin[p] == x(Dt[#1, x] & ) /@ %% /. Cos -> cosFirst[Solve[%, Dt[p, x]]]% /. cos[a_] -> Sqrt[1 - sin[p]^2]% /. sin[p] -> xBobby-----Original Message-----x's with the number at which it is trying to calculate the datapoint.Thisgives an error of Ôxxxx is not a valid variable'. Replacing D[test[x]]with test'[x] doesn't help either though it results in a different setoferrors. Is there any of way of getting around this problem?Farhat ==== =I have the _Mathematica Book_, /Third Edition/, and _Mathematica 3.0 Standard Add-on Packages_, as well as _Addendum to The Mathematica Book_ /A guide to the complete documentation for Mathematica 4.2?If I were starting form scratch, what books should I buy to form a complete set of 4.2 documentation?-- STHHatton's Law: There is only One inviolable Law. ==== =>> a potential division by 0 in ArcTan[y/x] ?>> Jens>> Is there any wisdom on whether one should employ or avoid the> 2-argument form of ArcTan[], versus ArcTan[y/x], in expressions> involving Solve[] and Integrate[]?>> Is there any harm? Is there any benefit?>The 2-argument form provides a bit more information since it takes thesigns of x and y into account and allows x to be zero. I imagine thiscould be helpful when used with Solve, but I don't know about Integrate.DavidReply-To: kuska@informatik.uni-leipzig.de ==== =a potential division by 0 in ArcTan[y/x] ? Jens> Is there any wisdom on whether one should employ or avoid the> 2-argument form of ArcTan[], versus ArcTan[y/x], in expressions> involving Solve[] and Integrate[]?> Is there any harm? Is there any benefit?> ==== =Dear groupI am looking for the simplest way to find EvaluationNotebook[]directory. The solution should work in all operatingdon't on Windows95/98 (Mathematica 4.1).StringDrop[DirectoryName[ToString[EvaluationNotebook[ ]]],17]Sincerely, Arturas Acus ==== =It looks as if you might profit enormously by taking a look at StephenWolfram's recent book, A New Kind of Science, where this and similarproblems are painstakingly discussed. In particular, in p. 611 of the bookyou have a plot of the Pascal triangle. The code used by Wolfram illustratesthe way Mathematica programming is used by the great gurus.Tomas GarzaMexico City----- Original Message -----rows> along the side of the large triangle and 2n - 1 columns along the base of> the triangle.>> This would be phase one of the project.>> Phase 2: Fill in the binomial coefficients into the triangle.> Phase 3: Color all odd numbered triangles blue.> Phase 4: Color all even numbered triangles red.> Phase 5: Any triangle that shares an edge with a red triangle, color red.>> The result is Zierpinski's Triangle! I have done this by hand for atriangle> with 16 rows. Needless to say the work was tedious. The result, however,is> quite satisfying and remarkable. I would like to be able to use this as a> tool to teach some of the other derivations that are possible fromPascal's> triangle other than binomial coefficients and combinations. Therefore it> would be beneficial to be able to reproduce this work at will.>> Since my Mathematica programming skills are practically nil, any helpwould> be appreciated.>> following:>> althemannon@attbi.com> ==== =Helo,I should thank you for this pleasent mind excercise, though not tough, itwas just basic geometry.$TextStyle={FontFamily->Verdana,FontSize->10};(* first create a basic object, a colored triangle with text inscribed, notethat the height of the triangle is a unit *)Triangle[j_,i_]:= Module[ { x0=(i-.5 j)2/Sqrt[3],y0=-j,a=2/Sqrt[3] }, { If[EvenQ[Binomial[j,i]],Hue[0,.5,1],Hue[.55,.5,1]], Polygon[{{x0,y0},{x0-.5 a,y0-1},{x0+.5 a,y0-1}}], GrayLevel[0],Text[ToString[Binomial[j,i]],{x0,y0-.5},{0,1}] } ](* the following command will show the agglomerate, note that it doesn'tdraw each of the triangles having no text, instead it draws a big triagle asa background and puts the numbered ones onto it *)ShowBigTriangle[jmax_]:= Show[ Graphics[ Prepend[ Table[Triangle[j,i],{j,0,jmax},{i,0,j}], {Hue[0,.5,1],Polygon[{{0,0},{-(jmax+1)/Sqrt[3],-(jmax+1)},{( jmax+1)/Sqrt[3],-(jmax+1)}}]} ] ] ,AspectRatio->Automatic ]ShowBigTriangle[33]//Timing(1.3 sec on my P2-350, how's your timming?)p.s. : According to S. Wolfram and his new kind of science, the solution toyour problem is just a simple program. He ilustrates this in 2nd Chapter. Itmay be worthy to take a peak.Bye,Borut| I want to write a program that will create an array of equilateraltriangles| such that in the first row there is 1 triangle, in the second row there is3| triangles, in the third row there will be 5 triangles...in the nth rowthere| will be 2n - 1 triangles. Putting all of these triangles together and| calling the first row, row 0, we would have a large triangle with n + 1rows| along the side of the large triangle and 2n - 1 columns along the base of| the triangle.|| This would be phase one of the project.|| Phase 2: Fill in the binomial coefficients into the triangle.| Phase 3: Color all odd numbered triangles blue.| Phase 4: Color all even numbered triangles red.| Phase 5: Any triangle that shares an edge with a red triangle, color red.|| The result is Zierpinski's Triangle! I have done this by hand for atriangle| with 16 rows. Needless to say the work was tedious. The result, however,is| quite satisfying and remarkable. I would like to be able to use this as a| tool to teach some of the other derivations that are possible fromPascal's| triangle other than binomial coefficients and combinations. Therefore it| would be beneficial to be able to reproduce this work at will.|| Since my Mathematica programming skills are practically nil, any helpwould| be appreciated.|| following:|| althemannon@attbi.com|| ==== =I want to write a program that will create an array of equilateral trianglessuch that in the first row there is 1 triangle, in the second row there is 3triangles, in the third row there will be 5 triangles...in the nth row therewill be 2n - 1 triangles. Putting all of these triangles together andcalling the first row, row 0, we would have a large triangle with n + 1 rowsalong the side of the large triangle and 2n - 1 columns along the base ofthe triangle.This would be phase one of the project.Phase 2: Fill in the binomial coefficients into the triangle.Phase 3: Color all odd numbered triangles blue.Phase 4: Color all even numbered triangles red.Phase 5: Any triangle that shares an edge with a red triangle, color red.The result is Zierpinski's Triangle! I have done this by hand for a trianglewith 16 rows. Needless to say the work was tedious. The result, however, isquite satisfying and remarkable. I would like to be able to use this as atool to teach some of the other derivations that are possible from Pascal'striangle other than binomial coefficients and combinations. Therefore itwould be beneficial to be able to reproduce this work at will.Since my Mathematica programming skills are practically nil, any help wouldbe appreciated.following:althemannon@attbi.com ==== =In the sampling with replacement I could find no improvement. In thesampling with replacement, I think you'd do well to abandon proceduralprogramming and use the many possibilities Mathematica offers to improveprogramming. Unfortunately, in spite of this I still couldn't find dramaticimprovements in speed (but then, I'm not a very skilled programmer). Itseems, however, that improvements in speed depend on the relative sizes ofyour data set and the sample.The idea is to use the AddOn package DiscreteMath`Combinatorica`, which hasa nice function RandomKSubset (cf. the Help Browser). Then I propose thefunction swor (it stands for sample without replacement):In[1]:=Needs[DiscreteMath`Combinatorica`]In[2]:= swor[data_List,n_]:=Module[ {ord=RandomKSubset[Length[data],n]}, data[[ord]]]It certainly looks simpler and nicer then your function SampelNoReplace.Now, I tried three combinations of data and sample sizes:In[44]:=Table[SampelNoReplace[Range[100],10],{10000}];/ /TimingOut[44]={3.282 Second,Null}In[45]:=Table[swor[Range[100],10],{10000}];// TimingOut[45]={2.906 Second,Null}In[42]:=Table[SampelNoReplace[Range[1000],30],{ 1000}];//TimingOut[42]={1.031 Second,Null}In[43]:=Table[swor[Range[1000],30],{1000}];// TimingOut[43]={0.641 Second,Null}In[46]:=Table[SampelNoReplace[Range[10000],100],{ 1000}];//TimingOut[46]={8.219 Second,Null}In[47]:=Table[swor[Range[10000],100],{1000}];// TimingOut[47]={2.312 Second,Null}So, as you see, in all cases we get some improvement, and it varies from 13%to 255%.Tomas GarzaMexico City----- Original Message ----->> SampelNoReplace[data_List, n_] := Module[{idx, len, res, d, hi, i},> d = data;> res = {};> len = hi = Length@d;>> For[i = 1, i <= n && i <= len, i++,> idx = Random[Integer, {1, hi--} ];> AppendTo[res, d[[idx]]];> d = Drop[d, {idx}];> ];> res> ]>> ==== => I've made two small rutines for sampling (bootstrap statistics)> They are working , but at least ÔSampleNoReplace' is rather slow> I was wondering if any of you know of a faster way to do this> SampelReplace[data_List:{0, 1}, n_:1] :=> Module[{}, data[[Table[Random[Integer, {1, Length@data} ], {n}]]]]> SampelNoReplace[data_List, n_] := Module[{idx, len, res, d, hi, i},> d = data;> res = {};> len = hi = Length@d;> For[i = 1, i <= n && i <= len, i++,> idx = Random[Integer, {1, hi--} ];> AppendTo[res, d[[idx]]];> d = Drop[d, {idx}];> ];> res> ]This comes up from time to time. Have a look athttp://forums.wolfram.com/mathgroup/archive/2001/Jan/ msg00087.htmlorhttp://forums.wolfram.com/mathgroup/archive/ 2001/Apr/msg00263.htmlDaniel LichtblauWolfram ResearchReply-To: ==== =I'm totally guessing, but I gather you want sampleNoReplace to return asample of size n from Ôdata', without duplications, with n>Length[data]resulting in a rearrangement of Ôdata'. If so, here's a simplesolution:ClearAll[sampleNoReplace, sampleReplace]sampleNoReplace[data_List, n_Integer?Positive] := Take[Sort[data, Random[] > 1/2 &], Min[n, Length[data]]]sampleReplace[data_List:{0, 1}, n_Integer:1] := data[[Table[Random[Integer, {1, Length@data}], {n}]]]There's no purpose for Module if you're not declaring local variables.Bobby-----Original Message----- d = data; res = {}; len = hi = Length@d; For[i = 1, i <= n && i <= len, i++, idx = Random[Integer, {1, hi--} ]; AppendTo[res, d[[idx]]]; d = Drop[d, {idx}]; ]; res ] ==== =certain level. I hate the thought of Multiplying and Dividing, but itlooks like the only workaround.A search of the archives shows that this is a real problem. I alsofound many complaints on not being able to Round Pi or E to somethingless than 16 digits. (Every solution affected the display, not thenumber) (Round[N[Pi*1000, 10]])/1000 // NReply Group button. -- Dana DeLouis Windows XP= = = = = = = = = = = = = = = = = ææ>Could somebody please inform me how to Round numbers to a>certain Accuracy using Mathematica 4.2.æ This is not as easy as it>sounds.>Every function that I have read Rounds the Display, and not theactual>number.> myRound[x_, n_] := Round[10^n*x]/10.^n;> Table[myRound[Random[], 3], {10}]> {0.044, 0.019, 0.738, 0.298, 0.917, 0.171, 0.021, 0.314, > æ 0.658, 0.153}>> Bob Hanlon ==== =The Format package from MathSource will do what you want:254>If I recall correctly, I had replace occurrences NProtectedAll by NHoldAll in Format.m to get it to work with Mathematica 4.2.Alex>> Can I also get the real fortran file, the file that it will be going > to be compiled. so the file begins at> 7-th column and ends at 72-th........> thanks for the help> alessandro agresti>> ==== =following command produces a satisfactory output when executed fromthe command line but when run in the Mathematica frontend, it producesan EPS file where the y-axis label looks like: Exp@xDExport[plot.eps, Plot[ Exp[x], {x,-1,1}, AxesLabel -> {x, Exp[x]} ]]Furthermore, the eps file produced by the frontend cannot be used withdvips: I get the error dvips: ! Couldn't find header file Mathematica2Mono.pfbIndeed, this file does not exist on my system.I _think_ I have followed all the instructions from Jens-Peer Juska'sThe Mathematica Virtual Font Package document distributed withMathematica but that doesn't seem to help.-NevinReply-To: kuska@informatik.uni-leipzig.de ==== =a) the FrontEnd used the Mathematica2.pfa font to draw (), [] and {}. Since your printer can not find the font it replace it by Courier and [] in Mathematica2 are @ and D in Courierb) find the wolfram.map file and replace the .pfb with .pfa when I prepare the file I had the binary fonts and it was not clear, if WRI will include the ASCII or the binary type 1 fonts. Jens> following command produces a satisfactory output when executed from> the command line but when run in the Mathematica frontend, it produces> an EPS file where the y-axis label looks like: Exp@xD> Export[plot.eps, Plot[ Exp[x], {x,-1,1}, AxesLabel -> {x,> Exp[x]} ]]> Furthermore, the eps file produced by the frontend cannot be used with> dvips: I get the error> dvips: ! Couldn't find header file Mathematica2Mono.pfb> Indeed, this file does not exist on my system.> I _think_ I have followed all the instructions from Jens-Peer Juska's> The Mathematica Virtual Font Package document distributed with> Mathematica but that doesn't seem to help.> -Nevin ==== =I would use Solve instead of FindRoot, and Part[[1,1,2]] instead ofPart[[1]]. Try this:In[1]:=test[x_] := Solve[Sin[p] == x, p]In[2]:=data[x_] := D[test[x][[1,1,2]], x]In[3]:=Plot[Evaluate[data[x]], {x, 0, 1}];Tomas GarzaMexico City----- Original Message ----->> Now, when trying to evaluate the derivative mathematica replaces both the> x's with the number at which it is trying to calculate the datapoint. This> gives an error of Ôxxxx is not a valid variable'. Replacing D[test[x]]> with test'[x] doesn't help either though it results in a different set of> errors. Is there any of way of getting around this problem?> Farhat> ==== => I am trying to evalute a function which looks like this. This is an> analogous problem not the actual problem.> test[x_] := p /. FindRoot[Sin[p] == x, {p, 1}][[1]]> data[x_] := D[test[x], x]> Plot[data[x], {x, 0, 1}]> Now, when trying to evaluate the derivative mathematica replaces both the> x's with the number at which it is trying to calculate the datapoint. This> gives an error of Ôxxxx is not a valid variable'. Replacing D[test[x]]> with test'[x] doesn't help either though it results in a different set of> errors. Is there any of way of getting around this problem?> FarhatIn addition to the ways noted in sci.math.symbolic (differentiatenumerically or form an interpolating function) I can think of one methodthat in essence reduces the plotting of the derivative to use the samecomputation as for evaluating the function itself. Like the othermethods, this one will not make use of the fact that your particularexample has a readily available inverse function.I'll show this using more customary notation {x,y}. We regard y as animplicitly defined function of x.expr[x_] = Sin[y]-xWe form the derivative with respect to x. We will use this to solve fory'[x] in terms of x and y[x].derivexpr = D[expr[x]/.y->y[x], x]Now we give a function to evaluate y[x] numerically.evaly[x_?NumberQ] := y /. FindRoot[expr[x]==0, {y,1}]We use all this to find an expression that will evaluate the derivativenumerically. We solve for y'[x] and then replace y[x] in the solution byevaly[x].In[8]:= evaldydx = (First[y'[x] /. Solve[derivexpr==0, y'[x]]]) /. y[x]->evaly[x]Out[8]= Sec[evaly[x]]This may now be plotted viaPlot[evaldydx, {x,0,1}]Daniel LichtblauWolfram Research ==== =There are a number of problems with what you are trying to do. I think rather than explaining what is wrong it may be more useful to indicate one approach that works.You can define your function as you did originally (assuming that was really what you wanted to do!)test[x_] := p /. FindRoot[Sin[p] == x, {p, 1}][[1]]Create a plot (contrary to the usual practice in such cases do not wrap Evaluate around the function to be plotted!)g = Plot[test[x], {x, 0, 1}]Now create an interpolating function from the graph:h = Interpolation[Cases[g, Line[{x__}] -> x, Infinity]]You can now plot the derivative:Plot[h'[t], {t, 0, 1}]>> I am trying to evalute a function which looks like this. This is an> analogous problem not the actual problem.>> test[x_] := p /. FindRoot[Sin[p] == x, {p, 1}][[1]]> data[x_] := D[test[x], x]> Plot[data[x], {x, 0, 1}]>> Now, when trying to evaluate the derivative mathematica replaces both > the> x's with the number at which it is trying to calculate the datapoint. > This> gives an error of Ôxxxx is not a valid variable'. Replacing D[test[x]]> with test'[x] doesn't help either though it results in a different set > of> errors. Is there any of way of getting around this problem?> Farhat>>Andrzej KozlowskiYokohama, Japanhttp://www.mimuw.edu.pl/~akoz/http:// platon.c.u-tokyo.ac.jp/andrzej/ ==== =Well, yes, perhaps a bit too naive. Bear in mind that 1) a 3D plot needsPlot3D; 2) The result of FindRoot is in the form of a rule wherefrom youhave to extract the actual value you need. Try this:In[1]:=sol[a_, b_] := FindRoot[a*Tanh[b*x] == x, {x, {0.01, 0.1}}]In[2]:=Plot3D[sol[a, b][[1,2]], {a, 1, 2}, {b, 1, 2}];Tomas GarzaMexico City----- Original Message -----> is solution.>> I've tried naively to do it as follows:>> sol[a_,b_]:=FindRoot[a*Tanh[b*x] == x, {x, {0.01, 0.1}}]> Plot[sol[a,b], {a, 1, 2}, {b, 1, 2}]>> And it doesn't work. Help me, please. What can I do?> Veniamin>> ==== =>-----Original Message----->Sent: Thursday, October 24, 2002 8:56 AM>To: mathgroup@smc.vnet.net>>I'd like to plot the solution of an equation which depends on two >parameters, e.g.>>a*Tanh[b*x] == x>>So, I'd like to see it in 3D, one axis is a, other is b, >and the last >is solution.>>I've tried naively to do it as follows:>>sol[a_,b_]:=FindRoot[a*Tanh[b*x] == x, {x, {0.01, 0.1}}]>Plot[sol[a,b], {a, 1, 2}, {b, 1, 2}]>>And it doesn't work. Help me, please. What can I do?>Veniamin>>Ëperhaps something like<< Graphics`Graphics3D`gtab = Table[ Plot[x /. FindRoot[a*Tanh[b*x] == x, {x, {0.001, 0.1}}], {a, 1, 1.01}, DisplayFunction -> Identity, PlotRange -> All, AxesOrigin -> {1, 0}], {b, 1, 1.01, .001}]Show[StackGraphics[gtab]]?--Harmut Wolf ==== =Soren,the very simple code here speeds up your procedure by a factor of about 150 for a data set of length 10000 and subsample length of 5000 (i.e. my code takes 0.06seconds where yours takes 9.6 seconds).< I've made two small rutines for sampling (bootstrap statistics)> They are working , but at least ÔSampleNoReplace' is rather slow> I was wondering if any of you know of a faster way to do this> SampelReplace[data_List:{0, 1}, n_:1] := > Module[{}, data[[Table[Random[Integer, {1, Length@data} ], {n}]]]]> SampelNoReplace[data_List, n_] := Module[{idx, len, res, d, hi, i},> d = data;> res = {};> len = hi = Length@d;> > For[i = 1, i <= n && i <= len, i++,> idx = Random[Integer, {1, hi--} ];> AppendTo[res, d[[idx]]];> d = Drop[d, {idx}];> ];> res> ]> <><><><><><><><><><><><>Johannes LudsteckEconomics DepartmentUniversity of RegensburgUniversitaetsstrasse 3193053 Regensburg ==== =While testing something yesterday I discovered some behaviour which Ihopedwould be handled better by Mathematica's $RecursionLimit. Is this adefectshow bwhich should be reported to WRI?It's a very simple example, in a notebook just type:foo[x_] = foo[foo[x]]You get the following error messages coming up one by one, with 4 beeps(used copy as->Plain text). All of these messages seem sensible.However,Mathematica then eats all the CPU, and if you don't abort memory usagegoesup and up until eventually I get a low virtual memory message fromWindows.I guess this is something to do with pattern matching in error results.In[1]:=foo[x_] = foo[foo[x]]$RecursionLimit::reclim: Recursion depth of !(256) exceeded.$RecursionLimit::reclim: Recursion depth of !(256) exceeded.$RecursionLimit::reclim: Recursion depth of !(256) exceeded.General::stop: Further output of !($RecursionLimit :: reclim)willbe suppressed during this calculation.$IterationLimit::itlim: Iteration limit of !(4096) exceeded.$IterationLimit::itlim: Iteration limit of !(4096) exceeded.$IterationLimit::itlim: Iteration limit of !(4096) exceeded.General::stop: Further output of !($IterationLimit :: itlim)willbe suppressed during this calculation.Platform: Mathematica 4.2 on both Windows XP and Mac OS XNick FortescueSmartspread Ltd.Reply-To: murray@math.umass.edu ==== =Under Mathematica 4.2, I obtain the same result as you -- off by 1 in the last decimal place displayed from what is shown in Maeder's book.That was on a Pentium 4 PC. Could it be that Maeder was using a different hardware platform, and that that alone would account for the difference? Actually, I'd be surprised if that were the reason, because I applied NumberForm[%, 15] to the result and obtained: 0.00157908413803032> I'm going through Dr. Maeder's book, _Compute Science with Mathematica_, > entering the examples into Mathematica and evaluating them. Here is my > current notebook:> http://baldur.globalsymmetry.com/proprietary/com/wri/ notebooks/csm-examples.nb> I've Noticed that in a few instances my results differ slightly from his. I'm > wondering why this is happeneing. One would expect that the same algorithm > would produce identical results regardless of the system on which it was run. > I'm running on 4.2, and it's certain Dr Míóder was using an earlier version. > Could that be the cause of the descrepency? > 0.00157909, whereas I get 0.00157908. This may not seem like a big deal, but > I heard of one company immediately losing a banking contract for accumulated > errors of this magnitude in their software. It sounds like a good way to > lose a space probe as well.> Any thoughts on this?> -- Murray Eisenberg murray@math.umass.eduMathematics & Statistics Dept.Lederle Graduate Research Tower phone 413 549-1020 (H)University of Massachusetts 413 545-2859 (W)710 North Pleasant StreetAmherst, MA 01375 ==== =I'm going through Dr. Maeder's book, _Compute Science with Mathematica_, entering the examples into Mathematica and evaluating them. Here is my current notebook:http://baldur.globalsymmetry.com/proprietary/com/wri /notebooks/csm-examples.nbI've Noticed that in a few instances my results differ slightly from his. I'm wondering why this is happeneing. One would expect that the same algorithm would produce identical results regardless of the system on which it was run. I'm running on 4.2, and it's certain Dr Míóder was using an earlier version. Could that be the cause of the descrepency? 0.00157909, whereas I get 0.00157908. This may not seem like a big deal, but I heard of one company immediately losing a banking contract for accumulated errors of this magnitude in their software. It sounds like a good way to lose a space probe as well.Any thoughts on this?-- STHHatton's Law: There is only One inviolable Law. ==== =Sorry if this is too easy but:I would like to simulate the shadows a house casts.I'll be getting Mathematica next week.Is there a package that will calculate the sun's position at a location on earth (given in degrees north/east) so I can set a lighting source accordingly?Marc Heusser-- Marc Heusserremove the obvious CHEERS and MERCIAL... from the reply address ==== =nice idea!At a first glance I learned that mathematica has not a very good coordinatesystem to do that.The sun is positioned according to a coord. system that corresponds toyour *look* at the system.Lets think further about this, as I said, I like the idea.The way of the sun might look like this (sorry, I copied directly from thenotebook):For[i=1,i[LessEqual] [Pi],i=i+[Pi]/10, Show[Graphics3D[Cuboid[{-1.5,-3,0},{1.5,3,4}]],PlotRange->{{- 5,5},{-5,5},{0,10}},LightSources[Rule]{{{Cos[i],0,Sin[i]}, RGBColor[0,1,0]}} ]] ==== =Below you will find a rather messy piece of code which seems to do what you wanted. It is messy because I have quickly adapted a (rather different) graphic representation of a Pascal triangle which I produced a couple of years ago at the request of another mathgroup contributor. The result is highly imperfect but I have no time to spend on improving it. Still it looks fine. The only thing I find strange is your request that only triangles that share an edge with a red triangle should be colored red. This leaves three types of triangles, red, blue and white. I think a Sierpinski (not Zierpinski!) triangle should only contain two colours. It was actually harder to make a three colored one, but that seemed to be what you requested. Here is my code:triangle1 = triangle = Table[{N[Sin[2*Pi*(n/3)]], N[Cos[2*Pi*(n/3)]]}, {n, 3}];triangle1[[3,2]] = -2;translate[l_List, v_] := (v + #1 & ) /@ l;tr[x_, y_] := Show[Graphics[Line /@ Partition[ Prepend[translate[triangle, {x, y}], Last[translate[triangle, {x, y}]]], 2, 1]], AspectRatio -> Automatic, DisplayFunction -> Identity];tr1[x_, y_] := Show[Graphics[If[Mod[Binomial[i, (i + j)/2], 2] == 1, {RGBColor[0, 0, 1], Polygon[translate[triangle, {x, y}]]}, {RGBColor[1, 0, 0], Polygon[translate[triangle, {x, y}]], Polygon[translate[triangle1, {x, y}]], Polygon[translate[triangle1, {x + Sqrt[3]/2, y + 3/2}]], Polygon[translate[triangle1, {x - Sqrt[3]/2, y + 3/2}]]}]], AspectRatio -> Automatic, DisplayFunction -> Identity];coords[i_, j_] := {j*(Sqrt[3]/2), (-3/2)*i};p[n_] := Table[tr @@ coords[i, j], {i, 0, n}, {j, -i, i, 2}];p1[n_] := Table[tr1 @@ coords[i, j], {i, 0, n}, {j, -i, i, 2}];label[i_, j_] := Text[Binomial[i, (i + j)/2], coords[i, j]];q[n_] := Graphics[Table[label[i, j], {i, 1, n}, {j, -i, i, 2}]];pascal[n_] := Show[p1[n], p[n], q[n], DisplayFunction -> $DisplayFunction, PlotRange -> {(-n)*(3/2) + 1, 1}];> I want to write a program that will create an array of equilateral > triangles> such that in the first row there is 1 triangle, in the second row > there is 3> triangles, in the third row there will be 5 triangles...in the nth row > there> will be 2n - 1 triangles. Putting all of these triangles together and> calling the first row, row 0, we would have a large triangle with n + > 1 rows> along the side of the large triangle and 2n - 1 columns along the base > of> the triangle.>> This would be phase one of the project.>> Phase 2: Fill in the binomial coefficients into the triangle.> Phase 3: Color all odd numbered triangles blue.> Phase 4: Color all even numbered triangles red.> Phase 5: Any triangle that shares an edge with a red triangle, color > red.>> The result is Zierpinski's Triangle! I have done this by hand for a > triangle> with 16 rows. Needless to say the work was tedious. The result, > however, is> quite satisfying and remarkable. I would like to be able to use this > as a> tool to teach some of the other derivations that are possible from > Pascal's> triangle other than binomial coefficients and combinations. Therefore > it> would be beneficial to be able to reproduce this work at will.>> Since my Mathematica programming skills are practically nil, any help > would> be appreciated.>> following:>> althemannon@attbi.com>>Andrzej KozlowskiYokohama, Japanhttp://www.mimuw.edu.pl/~akoz/http:// platon.c.u-tokyo.ac.jp/andrzej/ ==== => Can I also get the real fortran file, the file that it will be going to be compiled. so the file begins at > 7-th column and ends at 72-th........I thought FortranForm[] did this and inserted the necessary column-6continuation markers. IIRC, FortranForm[expr] > myfile.f can require somesimple post-editing to comply with fortran's columnar formatting rules.If your expression is at all complicated, it might be worth looking at FortranDef (Available fromwww.mathsource.com/MathSource/Enhancements/Interfacing/ Fortran/0202-172/FortranDef.nb)It optimises the expression for fortran compilation and produces nicelyformatted O/P. It is intended for use (with compilation) on Unix systems butworks fine at generating a fortran O/P file under Windows.Tom.-- Egham, Surrey, TW20 0EX, England. SPAN: 19.875Reply-To: kuska@informatik.uni-leipzig.de ==== =and Jens> Can I also get the real fortran file, the file that it will be going to be compiled. so the file begins at> 7-th column and ends at 72-th........> thanks for the help> alessandro agresti ==== =Can I also get the real fortran file, the file that it will be going to be compiled. so the file begins at 7-th column and ends at 72-th........thanks for the helpalessandro agresti ==== =>> This is not a high priority for me, but it would be nice to know how to> identify the source of such discrepancies.>In a program as large and complex and (dare I say it?) closed source as Mathematica that would be nearly impossible. Without access to actual instruction stream sent to the processor and knowledge of the processor state there is no way of determining the exact result of anything but the simplest ßoating point expression. In principle you could attach a debugger to the executing code but good luck in being able to determine which machine instructions correspond to the expression of interest in a program as large as Mathematica.Using some small C or Fortran programs in a debugger may help you probe your machine's and compiler's idiosyncrasies but that's not much help in determining how Mathematica operates.> I *believe* Java trys to create a platform neutral computing > environment which> insures results will be uniform across platforms. IIRC, I read > something> about this kind of thing in the Mathematica documentation. There are > ways of> manipulating the content of atoms which can be used to optimize > performance,> but they are discouraged because they can lead to the kinds of > discrepancies> were are discussing.... Indeed, see A.1.4 of the Mathematica Book: > (4.2, Help> Browser)>The information in A.1.4 seems to indicate that you have access to the underlying bit pattern in hexadecimal form of a ßoat or complex or other atomic type. It's not obvious to me that you can use these results to manipulate ßoating point computations though since the Raw representation is just that a representation and not a pointer to the actual data. Anyway the raw byte patterns of data still doesn't give you enough information. Returning to the example of Intel x86 versus most other architectures, if you set the processor state correctly multiplying two IEEE 754 ßoating point doubles (64-bit long ßoat) will result in an intermediate 80 bit IEEE ßoating point long double (that's why the register is 80 bits wide) which will then be converted back to an IEEE 754 ßoating point double when stored in memory. That 64 to 80 bit conversion is the source of many differences between identical numerical code on an x86 chip and other architectures.Java gets around this by disabling the 80 bit conversion. I have tried as much as possible to stay away from the details of x86 machine code as possible in my career so I don't know the details of the process but I believe it is possible to turn off the 64 to 80 bit conversion on x86 chips. However many JVMs now do JIT compilation, which converts large sections of Java code to optimized machine code for execution. Depending on the JIT compiler and hardware you use it is possible that a complex expression could be evaluated in different orders depending on the peculiarities of the pipeline structure of the processor. These guys (http://www.naturalbridge.com/ßoatingpoint/) seem to agree with me about JITs effect on Java's reproducibility problems. I'm not sure what the Java standard says about this though, but from page 41 of this paper (http://java.sun.com/people/darcy/JavaOne/2001/1789darcy.pdf) it seems there is a ßag that forces a JVM to force equivalent results on different architectures. There is probably a large performance penalty for this though.Finally section 3.1.6 of the Mathematica book seems to indicate that Mathematica will use whatever native ßoating point capabilities exist on a particular hardware platform. Again, this indicates to me that we can expect machine precision values to have 80 bit intermediate values in calculations on x86 (I'm not sure about IA-64) hardware. Also it is probably safe to assume that the Mathematica kernel is compiled to take advantage of the pipeline structure of whatever hardware it is running on and that machine precision expressions will be executed in the most efficient order possible on a particular hardware platform. The only way to test this is to create an expression whose result severely depends on the order of operations implied by parentheses then evaluate the expression with different parenthesization (is that a word?) to see if Mathematica respects the parentheses or internally reorders the expression into the most efficient form. I'm trying to think of an example right now, I'll post the results when available.> I do seem to recall a lost probe not too long ago. Seems someone > forgot to> convert from miles to kilometers, or something like that. To my mind > that was> just plain stupidity. They should never have been using imperial > units in> the first place.>There is also the story of the Ariane rocket (http://www.esrin.esa.it/htdocs/tidc/Press/Press96/ ariane5rep.html) that was lost due to not checking for out of range exceptions when converting from ßoating point values to integers. No process is perfect, including auditing the code.> Nonetheless, this demonstrates the kinds of things which can creep > into your> calculations. Suppose the Auditors come in and bless everything off, > and the> next week you get a brand new computer. Not realizing that the > hardware will> inßuence the outcome of your calculation, you copy everything over to > the> new system, give the nice lady at WRI a call to get your new password, > and> run the calculations 10 times faster, but based on assumptions which > are> inconsistent with your current environment. Ooops, Houston, we've > got a> problem.>The possibility of having to make that phone call is why I am glad I don't work for NASA ;-).At any rate If you were considering writing satellite launch or control code with Mathematica I suggest you examine the second paragraph of the Limited Warranty on your license agreement, in particular WRI does not recommend the use of the software for applications in which errors or omissions could threaten life, injury or significant loss.Ssezi ==== => following command produces a satisfactory output when executed from> the command line but when run in the Mathematica frontend, it produces> an EPS file where the y-axis label looks like: Exp@xD> Export[plot.eps, Plot[ Exp[x], {x,-1,1}, AxesLabel -> {x,> Exp[x]} ]]> Furthermore, the eps file produced by the frontend cannot be used with> dvips: I get the error> dvips: ! Couldn't find header file Mathematica2Mono.pfb> Indeed, this file does not exist on my system.> I _think_ I have followed all the instructions from Jens-Peer Juska's> The Mathematica Virtual Font Package document distributed with> Mathematica but that doesn't seem to help.Try configuring DVIPS so that it includes the path to the Type 1 Mathematica fonts. On your system, the fonts should be located in a directory with a paththat can be determined by evaluating the following expression in a kernel:ToFileName[{$TopDirectory, SystemFiles, Fonts, Type1}]This directory contains ASCII (.pfa) versions of the fonts, but DVIPSshould be capable of handling these fonts as well as their binaryequivalents.To find out how to adjust the DVIPS setting, check the documentation foryour implementation of TeX (e.g. teTeX, emTeX, etc.). It has been myexperience that the setting is in a plain text configuration file. However, the name of the file and the variable that you need to modifytends to vary among implementations.-- User Interface Programmer paulh@wolfram.comWolfram Research, Inc.Reply-To: ==== =sol[a_, b_] := Module[{x}, x /. FindRoot[a*Tanh[b*x] == x, {x, 0.01},AccuracyGoal -> 10]]Plot3D[sol[a, b], {a, 1, 2}, {b, 1, 2}]DrBob-----Original Message-----sol[a_,b_]:=FindRoot[a*Tanh[b*x] == x, {x, {0.01, 0.1}}]Plot[sol[a,b], {a, 1, 2}, {b, 1, 2}]And it doesn't work. Help me, please. What can I do?Veniamin ==== => I am looking for the simplest way to find EvaluationNotebook[]> directory. The solution should work in all operating> don't on Windows95/98 (Mathematica 4.1).> StringDrop[DirectoryName[ToString[EvaluationNotebook[ ]]],17]Here is a platform independent approach that uses the undocumented function NotebookInformation[].ToFileName[FileName /. NotebookInformation[EvaluationNotebook[]]]Bear in mind that if the notebook has not been saved with a file name, then the result will be the string FileName. A robust solution would include checking for this pathological situation.-- User Interface Programmer paulh@wolfram.comWolfram Research, Inc. ==== =I made a careless omission in writing my reply to this post. I forgot to include DirectoryName[]. The code snippet should have read:DirectoryName[ ToFileName[FileName /. NotebookInformation[EvaluationNotebook[]]]]I apologize for any confusion that this may have caused.-- User Interface Programmer paulh@wolfram.comWolfram Research, Inc. ==== =Veniamin,There are a few problems with your code that you need to addressbefore it will work:(i) The output from FindRoot is in the form of a replacement rule:x->something. And this will not work as input for the plottingroutine;(ii) You should use Plot3D not Plot;(iii) Your initial guess is not in the neighborhood of the root so youalways get x=0 (or its approximation)The following changes have been made and now your code woirkssol[a_, b_] := x /. FindRoot[a*Tanh[b*x] == x, {x, 2}]Plot3D[sol[a, b], {a, 1, 2}, {b, 1, 2}, PlotPoints -> 40]Brian> I'd like to plot the solution of an equation which depends on two > parameters, e.g.> a*Tanh[b*x] == x> So, I'd like to see it in 3D, one axis is a, other is b, and the last > is solution.> I've tried naively to do it as follows:> sol[a_,b_]:=FindRoot[a*Tanh[b*x] == x, {x, {0.01, 0.1}}]> Plot[sol[a,b], {a, 1, 2}, {b, 1, 2}]> And it doesn't work. Help me, please. What can I do?> VeniaminReply-To: Peltio ==== =>I'd like to plot the solution of an equation which depends on two>parameters, e.g.>sol[a_,b_]:=FindRoot[a*Tanh[b*x] == x, {x, {0.01, 0.1}}]>Plot[sol[a,b], {a, 1, 2}, {b, 1, 2}]You were almost there!The problem is the typo (Plot instead of Plot3D) and the fact that FindRoot,and hence sol, returns a replacement rule instead of the value of x.You will be better off with: sol[a_,b_]:=x /. FindRoot[a*Tanh[b*x] == x, {x, {0.01, 0.1}}] Plot3D[sol[a,b], {a, 1, 2}, {b, 1, 2}]And if you want to see the single points (here I use a grid with a spacingof 0.05 units) you can use this, instead: sol[a_,b_]:=FindRoot[a*Tanh[b*x]==x,{x,{0.01,0.1}}] vals=Flatten[Table[{a,b,x/.sol[a,b]},{a,1,2,.05},{b,1,2,.05}] ,1]; pts=Point/@vals; Show[Graphics3D[pts],BoxRatios[Rule]{1,1,1},Axes[Rule]True] cheers,Peltio-- ==== =First, there is always a trivial solution, i.e. x = 0.You are probably interested in the additional one, yes?. Depending on thevalues of a and b, it exists in Reals or it doesn't.I would carefully avoid continuous analysis in such problems and looked fora discrete solution. You can always increase resolution.Here we go.getSol[a_,b_,x_]:=FindRoot[Evaluate[a Tanh[b x] == x], {x,Sqrt[3 (a b-1)/(a b^3)]}]x/.Table[getSol[a,b,x],{a,1,2,.25},{b,1,2,.25}] ListDensityPlot[%](* continuous :) *)Plot3D[Evaluate[x/.getSol[a,b,x]],{a,1,2},{b,1,2}]A note : You should check for the critical a and b, i.e. where thenon-trivial solution vanishes. (e.g. a*b == 1). If you are thinking whereI've got the initial value for FindRoot, think twiceSeries[a Tanh[b x],{x,0,3}]//NormalHope that helps,Borut|| I'd like to plot the solution of an equation which depends on two| parameters, e.g.|| a*Tanh[b*x] == x|| So, I'd like to see it in 3D, one axis is a, other is b, and the last| is solution.|| I've tried naively to do it as follows:|| sol[a_,b_]:=FindRoot[a*Tanh[b*x] == x, {x, {0.01, 0.1}}]| Plot[sol[a,b], {a, 1, 2}, {b, 1, 2}]|| And it doesn't work. Help me, please. What can I do?||| Veniamin||||Reply-To: kuska@informatik.uni-leipzig.de ==== =*What* can youe do ? Read the manual carefull ?sol[a_?NumericQ, b_?NumericQ] := x /. FindRoot[a*Tanh[b*x] == x, {x, {0.01, 0.1}}]Plot3D[sol[a, b], {a, 1, 2}, {b, 1, 2}] Jens> I'd like to plot the solution of an equation which depends on two> parameters, e.g.> a*Tanh[b*x] == x> So, I'd like to see it in 3D, one axis is a, other is b, and the last> is solution.> I've tried naively to do it as follows:> sol[a_,b_]:=FindRoot[a*Tanh[b*x] == x, {x, {0.01, 0.1}}]> Plot[sol[a,b], {a, 1, 2}, {b, 1, 2}]> And it doesn't work. Help me, please. What can I do?> Veniamin ==== =I'd like to plot the solution of an equation which depends on two parameters, e.g.a*Tanh[b*x] == xSo, I'd like to see it in 3D, one axis is a, other is b, and the last is solution.I've tried naively to do it as follows:sol[a_,b_]:=FindRoot[a*Tanh[b*x] == x, {x, {0.01, 0.1}}]Plot[sol[a,b], {a, 1, 2}, {b, 1, 2}]And it doesn't work. Help me, please. What can I do?Veniamin ==== => -----Original Message-----> Sent: Friday, October 25, 2002 1:49 AM> To: mathgroup@smc.vnet.net> What I see is kind of like this, but with bigger parentheses:> (> a b> c d> )> I see the same thing you do; very strange.Perhaps a fix is in route as I type. I'll elaborate when I have more details.> I'm using version 4.2 and Windows XP Home. I hope that's not *my* fault. I solved my font problems. Which, BTW, cannot be blamed, in any way, on WRI. It seems it was a problem arising from my 8.0 -> 8.1 upgrade of SuSE. It may have resulted from an aborted upgrade which was caused by having Chi-Rho on the MBR of /dev/hda and LILO rather than GRUB as the boot manager. It's beyond the scope of this list to go into details, but since I fixed my fonts [see: http://baldur.globalsymmetry.com/proprietary/com/wri/ch05. html ]I haven't heard a single chirp about fonts, and haven't seen a single problem with missing or ugly fonts. Even problems which I would never have guessed were font related seem to have been corrected.A word of advice. Don't do all these on the same day:Build Mozilla from CVS (and use it to view MathML)Upgrade your operating systemBuild XEmacs from CVSInstall Mathematica 4.1 fontsUpgrade Mathematica from 4.1 to 4.2Install the CM fonts provided by AMSTry to learn to use MathML (especially using TreeForm[] in Mathematica 4.2.0, it's a known bug.) > (You should include that info when reporting this kind of problem.)Well smack my hand with a ruler, Teach! :-) You are absolutely correct. It > Bobby>-- STHHatton's Law: There is only One inviolable Law. ==== =In the first box of section 1.8.3, the matrix displayed seems to be badly fromatted. Is this what others also see? Is this just a Ôtypo'. IOW, an isolated minor problem, or is it indicative of something larger. I believe it is the former.Please don't think that all I'm doing is trying to find fault with Mathematica. And I'm not trying to be knit-picky. If it weren't for my previous problems - many of which seem to have stemmed from a font configuration problem introduced by an operating system upgrade - I would simply shrug this one badly formatted block off as a goof of some kind. The last time I noticed something like this, however, it turned into a few days worth of banging my head against a wall trying to figure out what was wrong.Please, someone, take a moment to look at this, and let me know what's up with it. What I see is kind of like this, but with bigger parentheses:( a b c d)-- STHHatton's Law: There is only One inviolable Law. ==== =This should put you on the right track:In[1]:=ListDensityPlot[{{1, 3}, {4, 7}}, Epilog -> {Hue[1], Text[1, {0.5, 1.5}], Text[2, {1.5, 1.5}], Text[3, {0.5, 0.5}], Text[4, {1.5, 0.5}]}]; Tomas GarzaMexico City----- Original Message ----- > -- > Dave Robinson> drobin@sandia.gov> ==== =I am currently using ListDensityPlot to view the contents of list. Iwould like to overlay the values of the list onto the resulting densityplot, perhaps as Ôred' numbers. I've done some digging but haven't seenanything similar, but I'm still pretty new to Mathematica so I may havemissed something. Any insights would be appreciated!-- Dave Robinsondrobin@sandia.gov ==== =David,ListDensityPlot[{{1, 2}, {3, 4}, {4, 5}},Epilog -> {Hue[0], MapIndexed[Text[#1, #2 - .5] &, Transpose[{{1, 2}, {3, 4}, {5, 6}}], {2}]}];--Allan---------------------Allan HayesMathematica Training and ConsultingLeicester UKwww.haystack.demon.co.ukhay@haystack.demon.co.ukVoice: +44 (0)116 271 4198> I am currently using ListDensityPlot to view the contents of list. I> would like to overlay the values of the list onto the resulting density> plot, perhaps as Ôred' numbers. I've done some digging but haven't seen> anything similar, but I'm still pretty new to Mathematica so I may have> missed something.>> Any insights would be appreciated!>> --> Dave Robinson> drobin@sandia.gov>> ==== => These seems to be the root of the problem. The file> $Topdir/SystemFiles/IncludeFiles/TeX/texmf/dvips/config/ wolfram.map>> contains lines like>> Mathematica2Mono Mathematica2Mono > and that leads to the error I describe above. If I change that to>> Mathematica2Mono Mathematica2Mono > then I no longer get the error. As you noted, the ASCII versions of> the font are present on my system. I'm not sure this is the> right fix since I don't understand dvips' font handling mechanism.This is the proper fix. I have verified that the typos in wolfram.map area known problem and that the errant file has been corrected for futurereleases. Sorry for the confusion difficulty this may have caused you.-- User Interface Programmer paulh@wolfram.comWolfram Research, Inc. ==== => I want to define a real-valued function f[t_] from the> values of a complex-valued function on a line parametrised> by t, and then be able to handle f like any other real> function (differentiate it etc.)> A cute example is:> Clear[rz, drz];> rz[t_] := Re[Zeta[1/2 + I*t]];> drz[t_] := D[rz[t], t] (* the sort of thing I want to do *)> so that> Plot[{drz[t], Im[Zeta[1/2 + I*t]]}, {t, 0, 40},> PlotStyle -> {RGBColor[1, 0, 0], RGBColor[0, 0, 1]}]> will work (it doesn't).> I can get a quick & dirty numerical approximation in this case> (including, as a reality check, the original function I'm> differentiating) using something like> Clear[rz, iz, rztable, plotzeta];> rz[t_] := Re[Zeta[1/2 + I*t]];> iz[t_] := Im[Zeta[1/2 + I*t]];> rztable[tmin_, tmax_] :=> Table[{t, rz[t]}, {t, tmin, tmax, (tmax - tmin)/50}];> plotzeta[tmin_, tmax_] := Module[{rzapprox},> rzapprox = Interpolation[rztable[tmin, tmax]];> Plot[{rzapprox'[t], rz[t], iz[t]}, {t, 0, 40},> PlotStyle -> {RGBColor[1, 0, 0], RGBColor[0, 1, 0],> RGBColor[0, 0, 1]}]> ]> plotzeta[0, 40]> However I'd prefer to leave the numerical approximations> till the last minute (i.e. plotting), and the interpolation> table would need tweaking on a case-by-case basis.> Any other suggestions? (sorry if there is an obvious answer).> -- Ewart Shaw> --> J.E.H.Shaw [Ewart Shaw] strgh@uk.ac.warwick TEL: +44 2476 523069> Department of Statistics, University of Warwick, Coventry CV4 7AL, U.K.> http://www.warwick.ac.uk/statsdept/Staff/JEHS/> 3 ((4&({*.(=+/))++/=3:)@([:,/0&,^:(i.3)@|:2^:2))&.>@]^:(i.@[) <#:3 6 2You can commute Re with D. To make use of this we'll unprotect Re andplace an UpValue for D on it.rz[t_] := Re[Zeta[1/2 + I*t]];Unprotect[Re];D[Re[a_],x_] ^:= Re[D[a,x]]We also want to work with a dummy variable even when we pass in a numberso we do a temporary substitution.drz[t_] := D[rz[x],x] /. x->tNow your plot should work fine.Daniel LichtblauWolfram Research ==== =I want to define a real-valued function f[t_] from thevalues of a complex-valued function on a line parametrisedby t, and then be able to handle f like any other realfunction (differentiate it etc.)A cute example is: Clear[rz, drz]; rz[t_] := Re[Zeta[1/2 + I*t]]; drz[t_] := D[rz[t], t] (* the sort of thing I want to do *) so that Plot[{drz[t], Im[Zeta[1/2 + I*t]]}, {t, 0, 40}, PlotStyle -> {RGBColor[1, 0, 0], RGBColor[0, 0, 1]}]will work (it doesn't).I can get a quick & dirty numerical approximation in this case(including, as a reality check, the original function I'm differentiating) using something like Clear[rz, iz, rztable, plotzeta]; rz[t_] := Re[Zeta[1/2 + I*t]]; iz[t_] := Im[Zeta[1/2 + I*t]]; rztable[tmin_, tmax_] := Table[{t, rz[t]}, {t, tmin, tmax, (tmax - tmin)/50}]; plotzeta[tmin_, tmax_] := Module[{rzapprox}, rzapprox = Interpolation[rztable[tmin, tmax]]; Plot[{rzapprox'[t], rz[t], iz[t]}, {t, 0, 40}, PlotStyle -> {RGBColor[1, 0, 0], RGBColor[0, 1, 0], RGBColor[0, 0, 1]}] ] plotzeta[0, 40]However I'd prefer to leave the numerical approximationstill the last minute (i.e. plotting), and the interpolation table would need tweaking on a case-by-case basis.Any other suggestions? (sorry if there is an obvious answer). -- Ewart Shaw-- J.E.H.Shaw [Ewart Shaw] strgh@uk.ac.warwick TEL: +44 2476 523069 Department of Statistics, University of Warwick, Coventry CV4 7AL, U.K. http://www.warwick.ac.uk/statsdept/Staff/JEHS/3 ((4&({*.(=+/))++/=3:)@([:,/0&,^:(i.3)@|:2^:2))&.>@]^:(i.@[) <#:3 6 2 ==== =Try MatrixForm[{{a,b},{c,d}}]. There is no typo.Tomas GarzaMexico City----- Original Message -----> previous problems - many of which seem to have stemmed from a font> configuration problem introduced by an operating system upgrade - I would> simply shrug this one badly formatted block off as a goof of some kind.The> last time I noticed something like this, however, it turned into a fewdays> worth of banging my head against a wall trying to figure out what waswrong.>> Please, someone, take a moment to look at this, and let me know what's upwith> it. What I see is kind of like this, but with bigger parentheses:> (> a b> c d> )> --> STH> Hatton's Law:> There is only One inviolable Law.> ==== => In the first box of section 1.8.3, the matrix displayed seems to be badly > fromatted. Is this what others also see? Is this just a Ôtypo'. IOW, an > isolated minor problem, or is it indicative of something larger. I believe > it is the former.The odd formatting that you observe is a side effect of setting the optionColumnWidths->{0.4, 0.6}, which is inherited from the style setting for aDefinitionBox in the HelpBrowser.nb style sheet.I am unsure if this is a bug in the math edit formatting or just a bad choice of values for this cell style. I have forwarded this example to our Quality Assurance department so that they may investigate this.If you find behavior that you believe to be errant, you are welcome to send concise examples to Wolfram Research Technical Support . This will ensure that our developers are aware of bugs that users find. Moreover, if it is a known problem with a simple workaround, they may be able to direct you to a frequently asked question page for more information.-- User Interface Programmer paulh@wolfram.comWolfram Research, Inc. ==== => This may be really simple but I am having trouble setting the> variables to the values returned by solve. If> solution={S0 -> 0,S1 -> 5....}the numbers of S# are subscripts> I can get to the idivdual parts with > solution[[1]][[1]] and solution[[1]][[2]] but when I try to set the> one equal to the other I get this error> Set::setps: solution[[1]] in assignment of part is not a symbol.> What is going on and how can I fix this?Perhaps you can use something like this:In[1]:= Solve[x + y == a && x - y == b, {x, y}] -(-a - b) -(-a + b)Out[1]= {{x -> ---------, y -> ---------}} 2 2In[2]:= % /. Rule[sym_,val_] :> Set[sym,val];In[3]:= x -(-a - b)Out[3]= --------- 2--Bhuvanesh,Wolfram Research. ==== => This may be really simple but I am having trouble setting the> variables to the values returned by solve. If> solution={S0 -> 0,S1 -> 5....}the numbers of S# are subscripts> I can get to the idivdual parts with> solution[[1]][[1]] and solution[[1]][[2]] but when I try to set the> one equal to the other I get this error> Set::setps: solution[[1]] in assignment of part is not a symbol.> What is going on and how can I fix this?Sam, you're working too hard :)If you really want permanent assignments, then substitute (Apply) Rule forSet:assignments=Set@@@solutionTom Burton ==== =Most likely to be improved, but at first glance:In[1]:=prod[a_List, b_List] := Table[Table[a[[i]] . Transpose[b][[j]], {j, 1, Dimensions[a][[1]]}], {i, 1, Dimensions[b][[2]]}]Tomas GarzaMexico City----- Original Message ----- Sender: steve@smc.vnet.netApproved: Steven M. Christensen , Moderator ==== =how do i write a code for matrix multiplication using mathematica. Ido not want to use the standard package but rather write the programmyself in mathematica. ==== =It seems to me that:Plot[Evaluate[{Re[D[Zeta[1/ 2 + I*t], t]], Re[Zeta[1/2 + I*t]]}], {t, 0, 40}, PlotStyle -> {RGBColor[ 1, 0, 0], RGBColor[0, 0, 1]}]should give you what you want?Andrzej KozlowskiYokohama, Japanhttp://www.mimuw.edu.pl/~akoz/http:// platon.c.u-tokyo.ac.jp/andrzej/On Friday, October 25, 2002, at 03:46 PM, > I want to define a real-valued function f[t_] from the> values of a complex-valued function on a line parametrised> by t, and then be able to handle f like any other real> function (differentiate it etc.)>> A cute example is:>> Clear[rz, drz];> rz[t_] := Re[Zeta[1/2 + I*t]];> drz[t_] := D[rz[t], t] (* the sort of thing I want to do *)>> so that>> Plot[{drz[t], Im[Zeta[1/2 + I*t]]}, {t, 0, 40},> PlotStyle -> {RGBColor[1, 0, 0], RGBColor[0, 0, 1]}]>> will work (it doesn't).> I can get a quick & dirty numerical approximation in this case> (including, as a reality check, the original function I'm> differentiating) using something like>> Clear[rz, iz, rztable, plotzeta];> rz[t_] := Re[Zeta[1/2 + I*t]];> iz[t_] := Im[Zeta[1/2 + I*t]];> rztable[tmin_, tmax_] :=> Table[{t, rz[t]}, {t, tmin, tmax, (tmax - tmin)/50}];> plotzeta[tmin_, tmax_] := Module[{rzapprox},> rzapprox = Interpolation[rztable[tmin, tmax]];> Plot[{rzapprox'[t], rz[t], iz[t]}, {t, 0, 40},> PlotStyle -> {RGBColor[1, 0, 0], RGBColor[0, 1, 0],> RGBColor[0, 0, 1]}]> ]>> plotzeta[0, 40]>> However I'd prefer to leave the numerical approximations> till the last minute (i.e. plotting), and the interpolation> table would need tweaking on a case-by-case basis.> Any other suggestions? (sorry if there is an obvious answer).> -- Ewart Shaw> -- > J.E.H.Shaw [Ewart Shaw] strgh@uk.ac.warwick TEL: +44 2476 > 523069> Department of Statistics, University of Warwick, Coventry CV4 7AL, > U.K.> http://www.warwick.ac.uk/statsdept/Staff/JEHS/> 3 ((4&({*.(=+/))++/=3:)@([:,/0&,^:(i.3)@|:2^:2))&.>@]^:(i.@[) <#:3 > 6 2> ==== => Dear All,> I am currently beginning to use the 4.2 version of Mathematica on winNT. I> find that the front end is very crash prone (a lot more then 4.1)... it> often crashes on editing things.> I am wondering if anyone experienced the same problems and if any solution> had already been found.> I have had similar problems with Mathematica 4.2 on a new Apple G4,running Mac OS 10.2. The crash sometimes happens when I am quitting Mathematica. It alsoseems to be more likely when I am closing a notebook (file), especiallyafter several openings and closing of notebooks. But I have alsoexperienced crashes when trying to bring up the on-line documentation.-- Chris Henrich ==== =Working with MathLink and Mathematica functions to manipulate notebooks I had the following problemI tried to make a MathLink function which before giving the final result, it sends to mathematica information about how the process is going on ( for example convergence of a variable or an index in a loop). The point is that printing all this could be very long ( a file is better in this case ) and I wanted a cell which is edited and deleted as the process goes on. The following function is a model of what iI intented/**************************************************** ***************/:Begin::Function: test:Pattern: test[]:Arguments: {}:ArgumentTypes: {}:ReturnType: Integer:End:/************************************************ ********************/int test(){ int i,j;for ( i=0;i<100 ;i++ ){ /* Sending the variable i to be displayed in Mathematica */ MLPutFunction(stdlink,EvaluatePacket,1); MLPutFunction(stdlink,CompoundExpression,2); MLPutFunction(stdlink,NotebookWrite,3); MLPutFunction(stdlink,SelectedNotebook,0); MLPutFunction(stdlink,Cell,2); MLPutFunction(stdlink,ToString,1); MLPutInteger(stdlink,i); MLPutString(stdlink,Program); MLPutSymbol(stdlink,All); MLPutSymbol(stdlink,Null); MLEndPacket(stdlink); MLFlush(stdlink); MLNewPacket(stdlink);} /* This is the final answer */ return 0;}/********************************************************* ***********/The function works fine until leaving the for loop. After that the link is lost. I can't fix this problem, I suppose that I don't treat the return packets in a proper way. I would be very greateful for any hints about thisCesar ==== =Try the followingMLNextPacket(stdlink); // drain packetMLNewPacket(stdlink); // discard packetInstead of ...MLEndPacket(stdlink);MLFlush(stdlink);MLNewPacket(stdlink) ;For more info, refer to Todd Gayley's, A Mathlink Tutorial (perhaps on MathSource).Lawrence> Working with MathLink and Mathematica functions to manipulate notebooks I had the following problem> I tried to make a MathLink function which before giving the final result, it sends to mathematica information about how the process is going on ( for example convergence of a variable or an index in a loop). The point is that printing all this could be very long ( a file is better in this case ) and I wanted a cell which is edited and deleted as the process goes on. The following function is a model of what iI intented> /************************************************************ *******/> :Begin:> :Function: test> :Pattern: test[]> :Arguments: {}> :ArgumentTypes: {}> :ReturnType: Integer> :End:> /************************************************************ ********/> int test()> {> int i,j;> for ( i=0;i<100 ;i++ )> { /* Sending the variable i to be displayed in Mathematica */> MLPutFunction(stdlink,EvaluatePacket,1);> MLPutFunction(stdlink,CompoundExpression,2);> MLPutFunction(stdlink,NotebookWrite,3);> MLPutFunction(stdlink,SelectedNotebook,0);> MLPutFunction(stdlink,Cell,2);> MLPutFunction(stdlink,ToString,1);> MLPutInteger(stdlink,i);> MLPutString(stdlink,Program);> MLPutSymbol(stdlink,All);> MLPutSymbol(stdlink,Null);> MLEndPacket(stdlink);> MLFlush(stdlink);> MLNewPacket(stdlink);> }> /* This is the final answer */> return 0;> }> /************************************************************ ********/> The function works fine until leaving the for loop. After that the link is lost. I can't fix this problem, I suppose that I don't treat the return packets in a proper way. I would be very greateful for any hints about this> Cesar > -- Lawrence A. Walker Jr.http://www.kingshonor.com ==== =In version 3.0 when I enter N[Pi,8], I get an output of 3.1415927 but the same input in version 4.2 gives an output of 3.14159. In fact, in version 4.2, N[Pi,k] for k between 0 and 16 gives an output of 3.14159 rather than a result with k digit precision. However, if k is 17 or more, I do get k digit precision in version 4.2. What happened to the k in N[expres,k] for k smaller than 17 in version 4.2. I have observed this in all calculations in Mathematica as I switched my lessons from 3.0 to 4.2. My students have reported the same problem. How do we get k Reply-To: jmt@dxdydz.net ==== =That's why you can use Mathematica arbitrary precision function to control your results.But you must know first what to control.> This is not surprising. First of all as you correctly pointed out the> Mathematica routines you are calling may have changed and therefore> produce different results.>> This is not a high priority for me, but it would be nice to know how to> identify the source of such discrepancies.>> Secondly your OS and hardware platform may> not be identical and in my experience the same compiler may produce> different results on different hardware and OS combinations due to> different optimizations applied to ßoating point expressions.> Finally, Intel chips have ßoating point registers that are actually 80> bits wide. Thus they perform some ßoating point operations> differently than a pure 64 bit machine because they may use 80 bits for> intermediate results. See> http://www.validlab.com/goldberg/addendum.html for a reasonable summary> of the issues with ßoating point computations on different> architectures.>> I *believe* Java trys to create a platform neutral computing environment> which insures results will be uniform across platforms. IIRC, I read> something about this kind of thing in the Mathematica documentation. There> are ways of manipulating the content of atoms which can be used to optimize> performance, but they are discouraged because they can lead to the kinds of> discrepancies were are discussing.... Indeed, see A.1.4 of the Mathematica> Book: (4.2, Help Browser)>> As an optimization for some special kinds of computations, the raw data in> Mathematica atomic objects can be given explicitly using Raw[head,> hexstring]. The data is specified as a string of hexadecimal digits,> corresponding to an array of bytes. When no special output form exists,> InputForm prints special objects using Raw. The behavior of Raw differs> from one implementation of Mathematica to another; its general use is> strongly discouraged. >> Any thoughts on this?>> If your ßoating point calculations are mission critical you have to> use a compiler which allows you to control whether ßoating point> expressions are optimized. Also you have to use a CPU architecture> whose behavior you understand. Finally all of your algorithms must be> analyzed to guarantee you understand and have compensated for the> ßoating point model of your compiler and CPU. This is why mission> critical code such as for NASA is typically audited by a team before> being committed to production code.>> I do seem to recall a lost probe not too long ago. Seems someone forgot to> convert from miles to kilometers, or something like that. To my mind that> was just plain stupidity. They should never have been using imperial units> in the first place.>> Nonetheless, this demonstrates the kinds of things which can creep into> your calculations. Suppose the Auditors come in and bless everything off,> and the next week you get a brand new computer. Not realizing that the> hardware will inßuence the outcome of your calculation, you copy> everything over to the new system, give the nice lady at WRI a call to get> your new password, and run the calculations 10 times faster, but based on> assumptions which are inconsistent with your current environment. Ooops, > Houston, we've got a problem.> Ssezi ==== => This is not surprising. First of all as you correctly pointed out the> Mathematica routines you are calling may have changed and therefore> produce different results. This is not a high priority for me, but it would be nice to know how to identify the source of such discrepancies.> Secondly your OS and hardware platform may> not be identical and in my experience the same compiler may produce> different results on different hardware and OS combinations due to> different optimizations applied to ßoating point expressions.> Finally, Intel chips have ßoating point registers that are actually 80> bits wide. Thus they perform some ßoating point operations> differently than a pure 64 bit machine because they may use 80 bits for> intermediate results. See> http://www.validlab.com/goldberg/addendum.html for a reasonable summary> of the issues with ßoating point computations on different> architectures.I *believe* Java trys to create a platform neutral computing environment which insures results will be uniform across platforms. IIRC, I read something about this kind of thing in the Mathematica documentation. There are ways of manipulating the content of atoms which can be used to optimize performance, but they are discouraged because they can lead to the kinds of discrepancies were are discussing.... Indeed, see A.1.4 of the Mathematica Book: (4.2, Help Browser)As an optimization for some special kinds of computations, the raw data in Mathematica atomic objects can be given explicitly using Raw[head, hexstring]. The data is specified as a string of hexadecimal digits, corresponding to an array of bytes. When no special output form exists, InputForm prints special objects using Raw. The behavior of Raw differs from one implementation of Mathematica to another; its general use is strongly discouraged. > Any thoughts on this?>> If your ßoating point calculations are mission critical you have to> use a compiler which allows you to control whether ßoating point> expressions are optimized. Also you have to use a CPU architecture> whose behavior you understand. Finally all of your algorithms must be> analyzed to guarantee you understand and have compensated for the> ßoating point model of your compiler and CPU. This is why mission> critical code such as for NASA is typically audited by a team before> being committed to production code.I do seem to recall a lost probe not too long ago. Seems someone forgot to convert from miles to kilometers, or something like that. To my mind that was just plain stupidity. They should never have been using imperial units in the first place. Nonetheless, this demonstrates the kinds of things which can creep into your calculations. Suppose the Auditors come in and bless everything off, and the next week you get a brand new computer. Not realizing that the hardware will inßuence the outcome of your calculation, you copy everything over to the new system, give the nice lady at WRI a call to get your new password, and run the calculations 10 times faster, but based on assumptions which are inconsistent with your current environment. Ooops, Houston, we've got a problem.>> Ssezi-- STHHatton's Law: There is only One inviolable Law. ==== => I've Noticed that in a few instances my results differ slightly from > his. I'm> wondering why this is happeneing. One would expect that the same > algorithm> would produce identical results regardless of the system on which it > was run.> I'm running on 4.2, and it's certain Dr Mç.94ç[Times]der was using an earlier > version.> Could that be the cause of the descrepency?>This is not surprising. First of all as you correctly pointed out the Mathematica routines you are calling may have changed and therefore produce different results. Secondly your OS and hardware platform may not be identical and in my experience the same compiler may produce different results on different hardware and OS combinations due to different optimizations applied to ßoating point expressions. Finally, Intel chips have ßoating point registers that are actually 80 bits wide. Thus they perform some ßoating point operations differently than a pure 64 bit machine because they may use 80 bits for intermediate results. See http://www.validlab.com/goldberg/addendum.html for a reasonable summary of the issues with ßoating point computations on different architectures.> Any thoughts on this?>If your ßoating point calculations are mission critical you have to use a compiler which allows you to control whether ßoating point expressions are optimized. Also you have to use a CPU architecture whose behavior you understand. Finally all of your algorithms must be analyzed to guarantee you understand and have compensated for the ßoating point model of your compiler and CPU. This is why mission critical code such as for NASA is typically audited by a team before being committed to production code.Ssezi ==== =I have been using mathematica for sometime now. However i havenever managed to get around the problem of correctly formattingmy documents. There is inevitable always a line formatting problem.Meaning if I type half way thru the line and without going all the wayin the same line go on to use the next line, for eg. when i am writingout step-wise, the solution to a particular probelm, then the next linecontents inevitably gets indented. Somehow I cant seem to get them leftalign correctly. For now I painstakingly do divide cell and merge themback to get the correct left alignment. however I am quite sure thatthere has to be a better solution.Can someone please advise. All my homeworks and papers are written inMathematica. like adding footnotes on a page, etc. - Shakti Shrivastava. ==== =Shakti,Look up indent in the Option Inspector (several entries).--Allan---------------------Allan HayesMathematica Training and ConsultingLeicester UKwww.haystack.demon.co.ukhay@haystack.demon.co.ukVoice: +44 (0)116 271 4198> I have been using mathematica for sometime now. However i have> never managed to get around the problem of correctly formatting> my documents. There is inevitable always a line formatting problem.>> Meaning if I type half way thru the line and without going all the way> in the same line go on to use the next line, for eg. when i am writing> out step-wise, the solution to a particular probelm, then the next line> contents inevitably gets indented. Somehow I cant seem to get them left> align correctly. For now I painstakingly do divide cell and merge them> back to get the correct left alignment. however I am quite sure that> there has to be a better solution.>> Can someone please advise. All my homeworks and papers are written in> Mathematica. like adding footnotes on a page, etc.> - Shakti Shrivastava.> ==== =Ray,Basically, the purpose of N is to change exact expressions to approximatenumber expressions. N has nothing directly to do with the display precision.To directly control the display precision use NumberForm.places. This can be changed through the Option Inspector. When you use N toconvert Pi, say, to an approximate number, it uses machine precision if k <=16. Otherwise, it uses an extended precision number and those numbers aredisplayed with the extended precision.So basically1) Use N to convert exact expressions to approximate number expressions.2) Use NumberForm to specifically control the display of numbers.3) Use the Option Inspector to change the default display precision ofmachine precision numbers.David Parkdjmp@earthlink.nethttp://home.earthlink.net/~djmp/ ==== = check out the option FormatType->FortranForm of Write2 of FeynCalc.At the end ofhttp://www.feyncalc.org/Write2/you find a simple example.Rolf MertigMertig Consultinghttp://www.mertig.com ==== =Check this thread of just a couple of days ago...http://forums.wolfram.com/mathgroup/archive/2002/Oct/ msg00422.html> Could someone please help me with a small problem, I have a magnetic> field> Bz[r,theta,z]> Btheta[r,theta,z]> Br[r,theta,z]> which I would like to plot with PlotVectorField3D, how do you go about> this given that PlotVectorField3D requires cartesian coordinates> Michael> ==== =Could someone please help me with a small problem, I have a magneticfieldBz[r,theta,z]Btheta[r,theta,z]Br[r,theta,z]which I would like to plot with PlotVectorField3D, how do you go aboutthis given that PlotVectorField3D requires cartesian coordinatesMichael ==== =This is not quite aposite to either NG, but there appear to be none better... My apologies.I am searching for an algorithm for producing a random derangement of, forinstance, the integers 1 to approx 10000.I thought Skiena's site might have such an algorithm, but I could not locateone. ... Producing all derangements and choosing one at random is marginallybeyond the capacity of my machine :-)Mark R. Diamond ==== =The vector field you want is {D[e[x,v],v], -D[e[x,v],x]}, (or its negative, depending what direction you want). The following adds this vector field to your implicit curves. < Identity]; vecs = PlotVectorField[vecßd, {x, xb1, xb2}, {v, vb1, vb2}, DisplayFunction -> Identity]; Show[curves, vecs, PlotRange -> rect, DisplayFunction -> $DisplayFunction];---Selwyn Hollis> I wish to do plot a vector field plot of an implicit solution.> Equations :> (*V[x] is a polynomial function defined earlier *)> e[x_, v_] := 1/2 v^2 + V[x];> t3 = Table[e[x, v] == e1, {e1, 0, 1, 0.2}];> ImplicitPlot[Evaluate[t3], {x, (-2), 2}];> This plots a nice implicit plot for various values of e1. What I wish to do is to attach a > sense to the contours (an arrow that describes the direction of the orbit).> However, I am at a loss as to how to do it with PlotVectorField.> Any help would be appreciated.> PS : Is there a way in which I can automate the labelling of the curves with the values > of e1 they are plotted for (something better than manually editing the labels to the plot > each time I change the range of e1) ?> Reply-To: spammers-go-here@yahoo.com ==== =I wish to do plot a vector field plot of an implicit solution.Equations :(*V[x] is a polynomial function defined earlier *)e[x_, v_] := 1/2 v^2 + V[x];t3 = Table[e[x, v] == e1, {e1, 0, 1, 0.2}];ImplicitPlot[Evaluate[t3], {x, (-2), 2}];This plots a nice implicit plot for various values of e1. What I wish to do is to attach a sense to the contours (an arrow that describes the direction of the orbit).However, I am at a loss as to how to do it with PlotVectorField.Any help would be appreciated.PS : Is there a way in which I can automate the labelling of the curves with the values of e1 they are plotted for (something better than manually editing the labels to the plot each time I change the range of e1) ?-- 3:29pm up 2:28, 1 user, load average: 0.07, 0.20, 0.16Reply-To: kuska@informatik.uni-leipzig.de ==== => This plots a nice implicit plot for various values of e1. What I wish to do is to attach a> sense to the contours (an arrow that describes the direction of the orbit).that is nonsense, because the direction of the orbit depend on yourinitialcondition. Start with a positive x'[t] and a negative x[t] and yourorbit is counter clock wise and with a negative x'[t] your orbit is clockwise. Jens> I wish to do plot a vector field plot of an implicit solution.> Equations :> (*V[x] is a polynomial function defined earlier *)> e[x_, v_] := 1/2 v^2 + V[x];> t3 = Table[e[x, v] == e1, {e1, 0, 1, 0.2}];> ImplicitPlot[Evaluate[t3], {x, (-2), 2}];> This plots a nice implicit plot for various values of e1. What I wish to do is to attach a> sense to the contours (an arrow that describes the direction of the orbit).> However, I am at a loss as to how to do it with PlotVectorField.> Any help would be appreciated.> PS : Is there a way in which I can automate the labelling of the curves with the values> of e1 they are plotted for (something better than manually editing the labels to the plot> each time I change the range of e1) ?> --> 3:29pm up 2:28, 1 user, load average: 0.07, 0.20, 0.16 ==== =Dear J/Link users,I put new Java Photo Editor application and staff on my web site.It's an interactive graphics environment for Mathematica frontend. It contains an example use of Java Photo Editor with Digital ImageProcessing package.Though it's still under development, it's main functionalities have beenachieved.The archive is available from this URL:http://fc.kuh.kumamoto-u.ac.jp/~jsato/jpe2002-oct24. zipAny comments will be appreciated.Junzo---------------------------------------- Junzo SATODepartment Of Medical Information Technology & Administration PlanningKumamoto University HospitalUniversity Of Kumamoto1-1-1 Honjo, Kumamoto City,Kumamoto, 860-8556, JAPANReply-To: tgarza01@prodigy.net.mx ==== =Well, this is rather strange. I obtained my first results on a Dell 4500,with 4.1, WinXP, 2.0 GHz, Pentium 4, 512Mb RAM. Since I'm away from homefor the weekend, I'm now using a Toshiba laptop, with 4.1, WinXP, 1.7 GHz,Pentium 4, 512Mb RAM. I copied the code from your message below andexecuted it. My new results are similar to the previous ones:In[1]:=Needs[ DiscreteMath`Combinatorica`]In[2]:=swor[data_List, n_] := Module[{ord = RandomKSubset[ Length[data], n]}, data[[ord]]]In[3]:=Timing[Table[swor[Range[100], 10], {10000}]; ]Out[3]={3.064 Second,Null}In[4]:=Timing[Table[swor[Range[1000], 30], {1000}]; ]Out[4]={0.762 Second,Null}In[5]:=Timing[Table[swor[Range[10000], 100], {1000}]; ]Out[5]={2.493 Second,Null}I can find no explanation for the differences with your timings, especiallyin the third case. Weird, isn't it?TomasOriginal Message:-----------------Timing[Table[swor[Range[1000], 30], {1000}]; ]{0.875*Second, Null}{2.609*Second, Null}Timing[Table[SampelNoReplace[Range[10000], 100], {1000}]; ]Timing[Table[swor[Range[10000], 100], {1000}]; ]{6.344000000000001*Second, Null}{31.436999999999998*Second, Null}As you can see, your method was generally much slower than the original,on my machine. Very strange!(However, the method I had posted was horribly slow --- so slow I won'tbother to post results for it.)Bobby-----Original Message-----your data set and the sample.The idea is to use the AddOn package DiscreteMath`Combinatorica`, whichhasa nice function RandomKSubset (cf. the Help Browser). Then I propose thefunction swor (it stands for sample without replacement):In[1]:=Needs[DiscreteMath`Combinatorica`]In[2]:= swor[data_List,n_]:=Module[ {ord=RandomKSubset[Length[data],n]}, data[[ord]]]It certainly looks simpler and nicer then your function SampelNoReplace.Now, I tried three combinations of data and sample sizes:In[44]:=Table[SampelNoReplace[Range[100],10],{10000}];/ /TimingOut[44]={3.282 Second,Null}In[45]:=Table[swor[Range[100],10],{10000}];// TimingOut[45]={2.906 Second,Null}In[42]:=Table[SampelNoReplace[Range[1000],30],{ 1000}];//TimingOut[42]={1.031 Second,Null}In[43]:=Table[swor[Range[1000],30],{1000}];// TimingOut[43]={0.641 Second,Null}In[46]:=Table[SampelNoReplace[Range[10000],100],{ 1000}];//TimingOut[46]={8.219 Second,Null}In[47]:=Table[swor[Range[10000],100],{1000}];// TimingOut[47]={2.312 Second,Null}So, as you see, in all cases we get some improvement, and it varies from13%to 255%.Tomas GarzaMexico City----- Original Message ----->> SampelNoReplace[data_List, n_] := Module[{idx, len, res, d, hi, i},> d = data;> res = {};> len = hi = Length@d;>> For[i = 1, i <= n && i <= len, i++,> idx = Random[Integer, {1, hi--} ];> AppendTo[res, d[[idx]]];> d = Drop[d, {idx}];> ];> res> ]>>---------------------------------------------------------- ---------- ==== =I've reached the conclusion that there is a great deal of good Mathematica material on the Web that is not at all easy to find. A Google search (e.g.) turns up dozens of useless links and very few of real interest, aside from obvious ones pointing to WRI. So I though it would be a worthwhile thread here to compile a current list of good Mathematica-related URLs of fairly general interest.The following are several that I think belong. Please chime in with any that you would add.1. Martin Krausshttp://wwwvis.informatik.uni-stuttgart.de/~kraus/ LiveGraphics3D2. Ted Ersek and Luci Ellishttp://www.verbeia.com/mathematica/3. Gianluca Gornihttp://www.dimi.uniud.it/~gorni/Mma/Mma.html4. David Parkhttp://home.earthlink.net/~djmp/Mathematica.html5. Mark McClurehttp://www.unca.edu/~mcmcclur/mathematicaGraphics/6. Jens-Peer Kuskahttp://phong.informatik.uni-leipzig.de/~kuska/7. The late Alfred Grayhttp://math.cl.uh.edu/~gray/8. U.S. Airforce Academyhttp://www.usafa.af.mil/dfms/mma.htm9. Selwyn Hollishttp://www.math.armstrong.edu/faculty/hollis/mmade/10. Steve Christensen/MathGrouphttp://smc.vnet.net/mathgroup.html11. Karl Unterkoßerhttp://www2.staff.fh-vorarlberg.ac.at/~ku/karl/ mma.htmlBy the way, there really ought to be a MathGroup FAQ page in the list.----Selwyn Hollis ==== =For readers interested in chemical engineering applications, they can look at:http://www.higgins.ucdavis.edu/chemmath.php.> I've reached the conclusion that there is a great deal of good > Mathematica material on the Web that is not at all easy to find. A > Google search (e.g.) turns up dozens of useless links and very few of > real interest, aside from obvious ones pointing to WRI. So I though it > would be a worthwhile thread here to compile a current list of good > Mathematica-related URLs of fairly general interest.> The following are several that I think belong. Please chime in with any > that you would add.> 1. Martin Krauss> http://wwwvis.informatik.uni-stuttgart.de/~kraus/ LiveGraphics3D> 2. Ted Ersek and Luci Ellis> http://www.verbeia.com/mathematica/> 3. Gianluca Gorni> http://www.dimi.uniud.it/~gorni/Mma/Mma.html> 4. David Park> http://home.earthlink.net/~djmp/Mathematica.html> 5. Mark McClure> http://www.unca.edu/~mcmcclur/mathematicaGraphics/> 6. Jens-Peer Kuska> http://phong.informatik.uni-leipzig.de/~kuska/> 7. The late Alfred Gray> http://math.cl.uh.edu/~gray/> 8. U.S. Airforce Academy> http://www.usafa.af.mil/dfms/mma.htm> 9. Selwyn Hollis> http://www.math.armstrong.edu/faculty/hollis/mmade/> 10. Steve Christensen/MathGroup> http://smc.vnet.net/mathgroup.html> 11. Karl Unterkoßer> http://www2.staff.fh-vorarlberg.ac.at/~ku/karl/mma.html> By the way, there really ought to be a MathGroup FAQ page in the list.> ----> Selwyn Hollis ==== =I would be glad to put together a MathGroup FAQ page, if I can get enough contributions to make it worthwhile.Those of you who have been regular contributors to MathGroup for a while, please think of a few FAQs and send them to me at this address: slhollis@earthlink.net. (Answers would be nice too.)---Selwyn Hollis> there is no group FAQ but the official FAQ page is> http://support.wolfram.com/mathematica/> But if Hartmut Wolf,Ted Ersek, you, David Park, Paul Abott,> I and some other regular posters prepare > an inofficial or MathGroup FAQ page with a> HTML part, a FAQ-pdf, FAQ notebook that goes beyond the> offcial pages it would be nice. > How would like to maintain and contribute ??> Jens>>By the way, there really ought to be a MathGroup FAQ page in the list.>>---->>Selwyn Hollis> Reply-To: kuska@informatik.uni-leipzig.de ==== =there is no group FAQ but the official FAQ page ishttp://support.wolfram.com/mathematica/But if Hartmut Wolf,Ted Ersek, you, David Park, Paul Abott,I and some other regular posters prepare an inofficial or MathGroup FAQ page with aHTML part, a FAQ-pdf, FAQ notebook that goes beyond theoffcial pages it would be nice. How would like to maintain and contribute ?? Jens> By the way, there really ought to be a MathGroup FAQ page in the list.> ----> Selwyn Hollis ==== =RE: Re: To plot solutions, FindRoot as a function-----Original Message-----Of course, there's also a negative solution: Series[a Tanh[b x]/x - 1, {x, 0, 3}] // Normal x /. Solve[% == 0, x] start[a_, b_] = First@% getSol[a_, b_] := x /. FindRoot[a Tanh[b x] == x, {x, start[a, b]}] Table[getSol[a, b], {a, 1, 2, .25}, {b, 1, 2, .25}]; ListDensityPlot[%] Plot3D[getSol[a, b], {a, 1, 2}, {b, 1, 2}] I tried using the 5-th degree series instead, and got nowhere! DrBob -----Original Message----- Here we go. getSol[a_,b_,x_]:=FindRoot[Evaluate[a Tanh[b x] == x], {x,Sqrt[3 (a b-1)/(a b^3)]}] x/.Table[getSol[a,b,x],{a,1,2,.25},{b,1,2,.25}] ListDensityPlot[%] (* continuous :) *) Plot3D[Evaluate[x/.getSol[a,b,x]],{a,1,2},{b,1,2}] A note : You should check for the critical a and b, i.e. where the non-trivial solution vanishes. (e.g. a*b == 1). If you are thinking where I've got the initial value for FindRoot, think twice Series[a Tanh[b x],{x,0,3}]//Normal Hope that helps, Borut | | I'd like to plot the solution of an equation which depends on two | parameters, e.g. | | a*Tanh[b*x] == x | | So, I'd like to see it in 3D, one axis is a, other is b, and the last | is solution. | | I've tried naively to do it as follows: | | sol[a_,b_]:=FindRoot[a*Tanh[b*x] == x, {x, {0.01, 0.1}}] | Plot[sol[a,b], {a, 1, 2}, {b, 1, 2}] | | And it doesn't work. Help me, please. What can I do? | | | Veniamin | | | | ==== =I would like to have mathematica attempt to find complex solutions to theequation:cos(cos(cos(cos x))) = sin(sin(sin(sin x)))It always tells me the variables appear to be related in a non-algebraicway. Is there a way to have it approximate these solutions?Reply-To: jbrowne@swin.edu.au ==== =Alexey,Below is a link to the draft of a book on Grassmann algebra. Although notthe full tensor algebra, it might give you some ideas for what can beachieved in Mathematica. I think you'll find Mathematica is ideal forencoding mathematical systems. The actual Grassmann algebra code is stillbeing finalized, but should be available early next year.http://www.ses.swin.edu.au/homes/browne/grassmannalgebra /book/index.htmJohn> Dear colleagues.>> Can anyone help me with making direct tensor algebra in Mathematica?>> In direct tensor algebra tensors are not components. Tensors are special> objects, that could be presented in the component form in sonme basis,> but even then they dont appear as S_{mn}, but as> S_{mn}r^m r^n> where r^m and r^n - are vectors of reciprocal basis and S_{mn} -> covariant components. NB! Basis vectors, are not columns like {1,0,0},> but exaclty vectors i.e. directed line segment as is.>> Is it possible to make this kind of package in Mathematica, that could> deal with such objects and also go to the component form - on the lower> level of abstraction - on demand.>> In particular such system would calculate that> a . b x a = 0 (mixed product - cross and dot) WITHOUT making the> constructs like> E^{mnk}b_m a_n a_k, where E^{mnk} - Levi-Chivitta symbols.>> The example is on leshakk.chat.ru - file tensor.pdf-- _________________________________John BrowneSchool of Engineering and ScienceSwinburne University of TechnologyJohn Street, Hawthorn, Victoria, AustraliaQuantica phone: +613 9431 4007Quantica fax: +613 9431 0940 ==== =Dear colleagues.Can anyone help me with making direct tensor algebra in Mathematica?In direct tensor algebra tensors are not components. Tensors are special objects, that could be presented in the component form in sonme basis, but even then they dont appear as S_{mn}, but asS_{mn}r^m r^nwhere r^m and r^n - are vectors of reciprocal basis and S_{mn} - covariant components. NB! Basis vectors, are not columns like {1,0,0}, but exaclty vectors i.e. directed line segment as is.Is it possible to make this kind of package in Mathematica, that could deal with such objects and also go to the component form - on the lower level of abstraction - on demand.In particular such system would calculate thata . b x a = 0 (mixed product - cross and dot) WITHOUT making the constructs likeE^{mnk}b_m a_n a_k, where E^{mnk} - Levi-Chivitta symbols.The example is on leshakk.chat.ru - file tensor.pdf ==== =I have a simple question:How can I print something without a linefeed, so that the next printingwill just continue the line.Ther must be an analogon to nRolfReply-To: kuska@informatik.uni-leipzig.de ==== =no, you can't because the kernel send a Print packedand the FrontEnd show it. But there is no continue packed. But you can accumulate the printed output in a string$printstring = myprint[a___] := ($printstring = StringJoin[$printstring, ToString[SequenceForm[a]]];)and show it withmyßush[]:=(Print[$printstring];$printstring=;) Jens> I have a simple question:> How can I print something without a linefeed, so that the next printing> will just continue the line.> Ther must be an analogon to n> Rolf ==== =I tried withSetAttributes[MyFunction, HoldRest]andSetAttributes[MyFunction, HoldAll]but the problem is that the main loop replaces the symbol Ôa' with itsvalue. For example fora = x^2;f[x_] := Print[x];SetAttributes[f, HoldAll];f[a]givesx^2I'd like to get something likea = x^2or just the symbol a. I looked at the attributes of Definition andFullDefinition, but they have just HoldAll and Protected. Maybe theyare special in some sense, and the main loop knows not to replace theargument with its value.Elcofres> MyFunction[a]>> and within MyFunction some variable gets assigned with a=x^2 (and not> just with x^2). Is there a way of doing this? I don't like having to> write MyFunction[a]. In some way Save seems to know how to tell the> system not to replace Ôa' with its value.> Save has the attribute HoldRest, you can attach this to MyFunction with> SetAttributes[MyFunction, HoldRest]> --> Allan> ---------------------> Allan Hayes> Mathematica Training and Consulting> Leicester UK> www.haystack.demon.co.uk> hay@haystack.demon.co.uk> Voice: +44 (0)116 271 4198>Reply-To: kuska@informatik.uni-leipzig.de ==== =a=x^2 is *not* a function, it is a value.The value of a symbol is stored inOwnValue[someSymbol]For a you will get{HoldPattern[a] :> x^2}and you have to work with this formand not with an assigment a=x^2, i.e.SetAttributes[OwnValueString, HoldAll]OwnValueString[from_Symbol] := Module[{own, st}, own = OwnValues[Unevaluated[from]] ; st = ToString[Unevaluated[from]]; StringReplace[ ToString[own /. HoldPattern[from] :> st /. Verbatim[HoldPattern][any_] :> any, InputForm], {:> -> =, -> }] ]will return the string {a=x^2} Jens> I'm trying to write a function similar to Save, but can't find how to> stop the main loop from evaluating the argument. Let's say I have the> definition> a=x^2> if I do> Save[filename,a]> the definition goes into the file, what I want is to get the> definition into a variable inside my function, so I can do:> MyFunction[a]> and within MyFunction some variable gets assigned with a=x^2 (and not> just with x^2). Is there a way of doing this? I don't like having to> write MyFunction[a]. In some way Save seems to know how to tell the> system not to replace Ôa' with its value.> TIA> Elcofres ==== =Elcofres> a=x^2 > is *not* a function, it is a value.> The value of a symbol is stored in> OwnValue[someSymbol]> For a you will get> {HoldPattern[a] :> x^2}> and you have to work with this form> and not with an assigment a=x^2, i.e.> SetAttributes[OwnValueString, HoldAll]> OwnValueString[from_Symbol] :=> Module[{own, st},> own = OwnValues[Unevaluated[from]] ;> st = ToString[Unevaluated[from]];> StringReplace[> ToString[own /. HoldPattern[from] :> st /. > Verbatim[HoldPattern][any_] :> any, InputForm], {:> -> =, > -> }]> ]> will return the string {a=x^2}> Jens> ==== => MyFunction[a]>> and within MyFunction some variable gets assigned with a=x^2 (and not> just with x^2). Is there a way of doing this? I don't like having to> write MyFunction[a]. In some way Save seems to know how to tell the> system not to replace Ôa' with its value.Save has the attribute HoldRest, you can attach this to MyFunction with SetAttributes[MyFunction, HoldRest]--Allan---------------------Allan HayesMathematica Training and ConsultingLeicester UKwww.haystack.demon.co.ukhay@haystack.demon.co.ukVoice: +44 (0)116 271 4198>> I'm trying to write a function similar to Save, but can't find how to> stop the main loop from evaluating the argument. Let's say I have the> definition>> a=x^2>> if I do>> Save[filename,a]>> the definition goes into the file, what I want is to get the> definition into a variable inside my function, so I can do:>> MyFunction[a]>> and within MyFunction some variable gets assigned with a=x^2 (and not> just with x^2). Is there a way of doing this? I don't like having to> write MyFunction[a]. In some way Save seems to know how to tell the> system not to replace Ôa' with its value.>> TIA> Elcofres> ==== = You can generate approximate solutions by using FindRoot insteadof Solve, but if you want complex solutions you have to indicate that.For example: FindRoot[Cos[Cos[Cos[Cos[x]]]]==Sin[Sin[Sin[Sin[x]]]],{x,1+i} ] Best, HarveyHarvey P. DaleUniversity Professor of Philanthropy and the LawDirector, National Center on Philanthropy and the LawNew York University School of LawRoom 206A110 West 3rd StreetNew York, N.Y. 10012-1074-----Original Message----- ==== =>I would like to have mathematica attempt to find complex solutions to the>equation:>>cos(cos(cos(cos x))) = sin(sin(sin(sin x)))>>It always tells me the variables appear to be related in a non-algebraic>way. Is there a way to have it approximate these solutions?>Clear[f];f[x_] := Cos[Cos[Cos[Cos[x]]]] - Sin[Sin[Sin[Sin[x]]]];Off[General::ovß, General::unß, FindRoot::frnum, FindRoot::cvnwt];Union[Select[Flatten[ Table[{x, Conjugate[x]} /. FindRoot[f[x], {x, xr + I*xi}, WorkingPrecision -> 25], {xr, -Pi/2, Pi/2, Pi/16}, {xi, Pi/16, Pi/2, Pi/16}]], Abs[f[#]] < 10^-15 &], SameTest -> (Abs[#1 - #2] < 10^-12 &)]Bob Hanlon ==== =David,to reply. I sincerely appreciate all your tips and mostly already follow allof them.However regarding this:> But I know that in my work it often happens that after I use ReturnMathematica indents> when I don't want it to. This is because Mathematica does not yet know if> the new line is a continuation of the previous statement. But when I begin> typing the new line Mathematica snaps it back to the left margin. Have you> tried that? (I also think there is some variation in Mathematica'sbehavior> here in various versions.)well that's a (very) slight problem coz then line (vertical) spacing isinconsistent.I assume that when you say>> But when I begin typing the new line Mathematica snaps it back to theleft>> margin.you mean you start typing in a new cell. In doing so Mathematica produces aline-break space greater than what is created by hitting return on thekeyboard.That's the main reason I type in a new cell to get correct left alignment,and thenmerge the cell back to get the correct (vertical) line spacing. Do you seewhat Iam saying?I wanted to know if there was a way to avoid this behavior. I mean workaroundthis in a more organized way if you will.Also do you know anyway of inserting footnotes? I really make use offootnotes inmy work .But currently don't know of a way to use them.it. - Sincerely Shakti.----- Original Message -----know> that in my work it often happens that after I use Return Mathematicaindents> when I don't want it to. This is because Mathematica does not yet know if> the new line is a continuation of the previous statement. But when I begin> typing the new line Mathematica snaps it back to the left margin. Have you> tried that? (I also think there is some variation in Mathematica'sbehavior> here in various versions.)>> You ask about good style for a notebook. This is, of course, a matter of> taste but I see an many dreadful notebooks so this gives me an excuse toset> forth some of my opinions.>> 1) The main purpose of a Mathematica notebook that you are sending to some> other person is to communicate your ideas and knowledge in as clear amanner> as possible. Anything that contributes to clarity is good, and anythingthat> detracts from it is bad. Remember that the reader is seldom going to spend> as much time reading the notebook as you spent making it. You have only a> limited shot at another person's mind.>> 2) Good notebooks are usually a fine mixture of Text cells, Input/Output> cells and graphics. The explanatory Text cells are equally as important as> the calculations. And for explanatory text use Text cells, not group> headings or Input cells. Text cells wrap, hyphenate and you can do spell> checking on them, and you can also include mathematical expressions with> Inline cells.>> 3) Make certain that the notebook has all necessary initializations and> definitions in it. As a check, quit the kernel and evaluate the notebookin> a fresh Mathematica session. A notebook that won't evaluate is certainlynot> going to convey your ideas.>> 4) If in any doubt about style, use the Default notebook style. Use cell> grouping and group headings to organize your notebook. For example, youcan> put all your initialization statements in an Initialization Section. Along> ungrouped, i.e., unorganized, notebook is difficult to navigate or follow.> With headings and grouping, and with the groups closed, the notebook> presents itself in outline form and already begins to convey your ideas.>> 5) STAY WITH THE DEFAULT AUTOMATIC GROUPING. I've seen many notebooks with> manual grouping. Without any exception whatever they were all perfectly> dreadful. They end up as one long totally unorganized mess.>> 6) Stay away from special formatting, colored cells and other special> effects. They may mean something to you but are nothing but clutter to the> reader. (It is too bad that WRI did not include some nice pastelBackground> colors for cells in the menu. The highly saturated colors are notsuitable.)>> Completely Evaluable> Text Cells - Input/Output Cells - Graphics> Get rid of all special effect clutter.>> David Park> djmp@earthlink.net> http://home.earthlink.net/~djmp/>> I have been using mathematica for sometime now. However i have> never managed to get around the problem of correctly formatting> my documents. There is inevitable always a line formatting problem.>> Meaning if I type half way thru the line and without going all the way> in the same line go on to use the next line, for eg. when i am writing> out step-wise, the solution to a particular probelm, then the next line> contents inevitably gets indented. Somehow I cant seem to get them left> align correctly. For now I painstakingly do divide cell and merge them> back to get the correct left alignment. however I am quite sure that> there has to be a better solution.>> Can someone please advise. All my homeworks and papers are written in> Mathematica. like adding footnotes on a page, etc.> - Shakti Shrivastava.>> ==== =Shakti,Your method of doing multiple steps in a single cell is a good one.Especially, it is a way to group related steps and use % and %% withoutambiguity as to what they stand for. I was trying to reproduce an example ofwhat you are talking about and couldn't come up with a good one. But I knowthat in my work it often happens that after I use Return Mathematica indentswhen I don't want it to. This is because Mathematica does not yet know ifthe new line is a continuation of the previous statement. But when I begintyping the new line Mathematica snaps it back to the left margin. Have youtried that? (I also think there is some variation in Mathematica's behaviorhere in various versions.)You ask about good style for a notebook. This is, of course, a matter oftaste but I see an many dreadful notebooks so this gives me an excuse to setforth some of my opinions.1) The main purpose of a Mathematica notebook that you are sending to someother person is to communicate your ideas and knowledge in as clear a manneras possible. Anything that contributes to clarity is good, and anything thatdetracts from it is bad. Remember that the reader is seldom going to spendas much time reading the notebook as you spent making it. You have only alimited shot at another person's mind.2) Good notebooks are usually a fine mixture of Text cells, Input/Outputcells and graphics. The explanatory Text cells are equally as important asthe calculations. And for explanatory text use Text cells, not groupheadings or Input cells. Text cells wrap, hyphenate and you can do spellchecking on them, and you can also include mathematical expressions withInline cells.3) Make certain that the notebook has all necessary initializations anddefinitions in it. As a check, quit the kernel and evaluate the notebook ina fresh Mathematica session. A notebook that won't evaluate is certainly notgoing to convey your ideas.4) If in any doubt about style, use the Default notebook style. Use cellgrouping and group headings to organize your notebook. For example, you canput all your initialization statements in an Initialization Section. A longungrouped, i.e., unorganized, notebook is difficult to navigate or follow.With headings and grouping, and with the groups closed, the notebookpresents itself in outline form and already begins to convey your ideas.5) STAY WITH THE DEFAULT AUTOMATIC GROUPING. I've seen many notebooks withmanual grouping. Without any exception whatever they were all perfectlydreadful. They end up as one long totally unorganized mess.6) Stay away from special formatting, colored cells and other specialeffects. They may mean something to you but are nothing but clutter to thereader. (It is too bad that WRI did not include some nice pastel Backgroundcolors for cells in the menu. The highly saturated colors are not suitable.)Completely EvaluableText Cells - Input/Output Cells - GraphicsGet rid of all special effect clutter.David Parkdjmp@earthlink.nethttp://home.earthlink.net/~djmp/there has to be a better solution.Can someone please advise. All my homeworks and papers are written inMathematica. like adding footnotes on a page, etc. - Shakti Shrivastava. ==== =I must admit, Mathematica looks a lot different to me after having done some real programming in Java, than it did a few years ago. I understand it much better, but I also find myself grasping for things that don't seem to be native to the product/language.There seems to be virtually no native support for OOP in Mathematica. Am I understanding things correctly? Dr. Míóder (I'm being a bit stubborn here - use UTF-8) provides his own object package with his Computer Science with Mathematica. I haven't worked with yet, but by looking it over, it seems a bit kluged ( http://www.dict.org/bin/Dict?Form=Dict2&Database=*&Query= kluge ). I don't mean to upbraid Dr. Míóder's attempt to add functionality which probably should be a native part of the Mathematica language. Perhaps I'll get used to the approach he has used, but for now, I must say, it seems awkward. My guess is Dr. Míóder did the best that could be expected with the constraints under which he was working.It is inconceivable to me that I am the first person to question the lack of native OO support in Mathematica. There must be a history of discussion on this topic. Is anybody aware of a record of such? Am I not understanding things correctly? Do others believe OO support is lacking in Mathematica, and really Ôshould' be here?-- STHHatton's Law: There is only One inviolable Law. ==== =OO adds data types and member functionw to Mathematica, in order to makeMathematica more usefulHermann Schmitt----- Original Message ----->> The natural way of thinking is:> I wish to do something and you exectue the function that> does this something.>> and not> What data are needed to do the job and what> else can I do with the data?>> Since Mathematica know nothing about data types> it is useless to add member-functions to the> non existing data types.>> But you can overload an existing function> and extend it's usage.>> Jens> I must admit, Mathematica looks a lot different to me after having donesome> real programming in Java, than it did a few years ago. I understand itmuch> better, but I also find myself grasping for things that don't seem to be> native to the product/language.>> There seems to be virtually no native support for OOP in Mathematica. AmI> understanding things correctly? Dr. Míóder (I'm being a bit stubbornhere -> use UTF-8) provides his own object package with his Computer Sciencewith> Mathematica. I haven't worked with yet, but by looking it over, itseems a> bit kluged (http://www.dict.org/bin/Dict?Form=Dict2&Database=*&Query= kluge> ). I don't mean to upbraid Dr. Míóder's attempt to add functionalitywhich> probably should be a native part of the Mathematica language. PerhapsI'll> get used to the approach he has used, but for now, I must say, it seems> awkward. My guess is Dr. Míóder did the best that could be expectedwith the> constraints under which he was working.>> It is inconceivable to me that I am the first person to question thelack of> native OO support in Mathematica. There must be a history of discussionon> this topic. Is anybody aware of a record of such? Am I notunderstanding> things correctly? Do others believe OO support is lacking inMathematica,> and really Ôshould' be here?> --> STH> Hatton's Law:> There is only One inviolable Law.>Reply-To: kuska@informatik.uni-leipzig.de ==== =what is a member functionw to Mathematica ?A Global`* a System`* ...There exist nothing that become more useful withobject oriented programming. Jens> OO adds data types and member functionw to Mathematica, in order to make> Mathematica more useful> Hermann SchmittReply-To: kuska@informatik.uni-leipzig.de ==== =NO ! objects Ôshould' not be here. You are using a functional programming languagethat is much better than OOP can ever be.OOP is for data & data types. The natural way of thinking is:I wish to do something and you exectue the function thatdoes this something.and notWhat data are needed to do the job and what else can I do with the data?Since Mathematica know nothing about data typesit is useless to add member-functions to thenon existing data types.But you can overload an existing function and extend it's usage. Jens> I must admit, Mathematica looks a lot different to me after having done some> real programming in Java, than it did a few years ago. I understand it much> better, but I also find myself grasping for things that don't seem to be> native to the product/language.> There seems to be virtually no native support for OOP in Mathematica. Am I> understanding things correctly? Dr. Míóder (I'm being a bit stubborn here -> use UTF-8) provides his own object package with his Computer Science with> Mathematica. I haven't worked with yet, but by looking it over, it seems a> bit kluged ( http://www.dict.org/bin/Dict?Form=Dict2&Database=*&Query= kluge> ). I don't mean to upbraid Dr. Míóder's attempt to add functionality which> probably should be a native part of the Mathematica language. Perhaps I'll> get used to the approach he has used, but for now, I must say, it seems> awkward. My guess is Dr. Míóder did the best that could be expected with the> constraints under which he was working.> It is inconceivable to me that I am the first person to question the lack of> native OO support in Mathematica. There must be a history of discussion on> this topic. Is anybody aware of a record of such? Am I not understanding> things correctly? Do others believe OO support is lacking in Mathematica,> and really Ôshould' be here?> --> STH> Hatton's Law:> There is only One inviolable Law. ==== =Bonjour,Je recherche le serial version europe pour Mathematica 4.x !Il en existe une multitude pour la version am.8ericaine (englais) mais paspour la version europ.8eene, ce qui me permettrait d'installer le kit delangue fran.8daise.Si qqun utilise mathematica avec le kit fran.8dais... je serais interess.8e parle serial du soft.Enfin, simplement un no de license type Europe.Merci ! ==== =The following function (for 3 arrays) is given:q[x_] := { { {q1*x/l1}, {x, 0, l1} }, { {-q2}, {x, l1, l2} }, { {(-q2)*(x^2/l3^2 - 2*x/l3 + 1)}, {x, l2, l3} } }as an example, in the array x=l1->l2 the function q[x]=-q2.The number of arrays can change.I have to find out the function for w[x] wherew''''[x]=q[x ].The transition condition arew_1[x]=w_2[x];w_1'[x]=w_2'[x];w_1[CapitalO Tilde][x]=w_2'[x];where 1 and 2 indicate the arrays. Arrays 2 and 3 (and 3-4, 4-5,...) have to satisfy the same conditions.How can I solve the problem? I first thought that a combination of ÔDSolve' and ÔDo' can do it, but I was wrong.Stefan ==== =Roman Maeder's package is meant for teaching computer science not for general use. Whether Mathematica would benefit from OO functionality has been a matter of some very heated debate, which you can find in this groups archives.Personally I am somewhere in the middle on this. I think it would be useful for developing packages for some very highly structured areas of mathematics (e.g. Algebraic Geometry). But for most applications in mathematics and physics the mixture of pattern based and functional programming offered by Mathematica is close to ideal and an additional programming paradigm would just get in the way. I don't think we need built in support for OOP in Mathematica but I am sure many would welcome a good AddOn package.Andrzej KozlowskiYokohama, Japanhttp://www.mimuw.edu.pl/~akoz/http:// platon.c.u-tokyo.ac.jp/andrzej/> I must admit, Mathematica looks a lot different to me after having > done some> real programming in Java, than it did a few years ago. I understand > it much> better, but I also find myself grasping for things that don't seem to > be> native to the product/language.>> There seems to be virtually no native support for OOP in Mathematica. > Am I> understanding things correctly? Dr. Mç.94ç[Times]der (I'm being a bit stubborn > here -> use UTF-8) provides his own object package with his Computer Science > with> Mathematica. I haven't worked with yet, but by looking it over, it > seems a> bit kluged ( > http://www.dict.org/bin/Dict?Form=Dict2&Database=*&Query= kluge> ). I don't mean to upbraid Dr. Mç.94ç[Times]der's attempt to add functionality > which> probably should be a native part of the Mathematica language. Perhaps > I'll> get used to the approach he has used, but for now, I must say, it seems> awkward. My guess is Dr. Mç.94ç[Times]der did the best that could be expected > with the> constraints under which he was working.>> It is inconceivable to me that I am the first person to question the > lack of> native OO support in Mathematica. There must be a history of > discussion on> this topic. Is anybody aware of a record of such? Am I not > understanding> things correctly? Do others believe OO support is lacking in > Mathematica,> and really Ôshould' be here?> -- > STH> Hatton's Law:> There is only One inviolable Law.>> ==== => Under Mathematica 4.2, I obtain the same result as you -- off by 1 in> the last decimal place displayed from what is shown in Maeder's book.>> That was on a Pentium 4 PC. Could it be that Maeder was using a> different hardware platform, and that that alone would account for the> difference? Actually, I'd be surprised if that were the reason, > because> I applied NumberForm[%, 15] to the result and obtained:>> 0.00157908413803032>I get exactly the same result on a PowerPC G4. Perhaps there is a typo?Sseziwa ==== =I'm running Mathematica 4.1 on Windoze XP, and have some newbiecombination/permutation questions, and am hoping that the collectivewisdom of this newsgroup can help/guide me out! ;)First, suppose that I have 4 objects, a, b, c, and d, respectively. How can I generate the permutation set when chosing, say, only *2*elements.In[1]:= Permutations[{a,b,c,d}]gives me the permutation set when choosing *all* 4 objects ... :(Second, for the same four objects (a,b,c,d), to generate the*combination* set (with 2 elements), I use:In[2]:= Needs[DiscreteMath`Combinatorica`];In[3]:= cset=KSubsets[{a,b,c,d},2]and this generates the expected 6 combinatorial pairs({{a,b},{a,c},{a,d},{b,c},{b,d},{c,d}}).What I'd like to do next is add each combinatorial set, and I am ableto do this correctly via:In[4]:= Plus@@Transpose[cset]to obtain {a+b,a+c,a+d,b+c,b+d,c+d}.My problem lies in the fact that now, I'd like to be able to allow*each* (a,b,c,d) element to be either plus, or minus (in reality, I'mtrying to generate combinatorial adds/minuses for *functions*(a,b,c,d)), and to still generate the Ôsum' of the cominatorial set. So for instance, in my current example, for the *first* {a,b}combinatorial pair, I'd like to be able to generateIn[5]:= Plus@@Transpose[Partition[Flatten[Outer[List,{a,-a},{b,-b}]], 2]](which generates {a+b,a-b,-a+b,-a-b}) ... only I'd like this to besomehow done automatically for *each* combinatorial pair (and, for themore general case when I generate combinatorial sets involving only'k' elements). I've struggled with this for a while, and am only ableto generate such a list *manually* for each of my six originalcombinatorial pairs ... a tedious, and somewhat tiresome procedure! :( Is there a way of Ôeasily' doing this?!?With my newly generated list (having 4*6 Ôelements'), how can I alsogo about finding which expressions involve/use only, say, 1 Minus? Isthere an Ôeasy' way of doing this too? (For instance, I'd like tothen Ôfilter' for (a-b) and (b-a) ...) (Perhaps the count of 1 Minusis a little contrived for this example here, but for the more generalcase I'll probably be considering, I might need to filter for, say,(longer) expressions involving 2 Minuses (say).)feedback and help would be most welcome and appreciated!Michael ==== =Michael,For the latter part of your question: Needs[DiscreteMath`Combinatorica`]; data={a,b,c,d}; Flatten[{#+#2,#1-#2,-#1+#2,-#1-#2}&@@ Transpose[KSubsets[data,2]]] {a+b,a+c,a+d,b+c,b+d,c+d,a-b,a-c,a-d,b-c,b-d, c-d,-a+b,-a+c,-a+d,-b+c,-b+d,-c+d,-a-b,-a-c,-a-d,-b-c,-b-d,- c-d} Flatten[{#1-#2,-#1+#2}&@@ Transpose[KSubsets[data,2]]] {a-b,a-c,a-d,b-c,b-d,c-d,-a+b,-a+c,-a+d,-b+c,-b+d,-c+d}-- Allan---------------------Allan HayesMathematica Training and ConsultingLeicester UKwww.haystack.demon.co.ukhay@haystack.demon.co.ukVoice: +44 (0)116 271 4198>> I'm running Mathematica 4.1 on Windoze XP, and have some newbie> combination/permutation questions, and am hoping that the collective> wisdom of this newsgroup can help/guide me out! ;)>> First, suppose that I have 4 objects, a, b, c, and d, respectively.> How can I generate the permutation set when chosing, say, only *2*> elements.>> In[1]:= Permutations[{a,b,c,d}]>> gives me the permutation set when choosing *all* 4 objects ... :(>> Second, for the same four objects (a,b,c,d), to generate the> *combination* set (with 2 elements), I use:>> In[2]:= Needs[DiscreteMath`Combinatorica`];> In[3]:= cset=KSubsets[{a,b,c,d},2]>> and this generates the expected 6 combinatorial pairs> ({{a,b},{a,c},{a,d},{b,c},{b,d},{c,d}}).>> What I'd like to do next is add each combinatorial set, and I am able> to do this correctly via:>> In[4]:= Plus@@Transpose[cset]>> to obtain {a+b,a+c,a+d,b+c,b+d,c+d}.>> My problem lies in the fact that now, I'd like to be able to allow> *each* (a,b,c,d) element to be either plus, or minus (in reality, I'm> trying to generate combinatorial adds/minuses for *functions*> (a,b,c,d)), and to still generate the Ôsum' of the cominatorial set.> So for instance, in my current example, for the *first* {a,b}> combinatorial pair, I'd like to be able to generate>> In[5]:= Plus@@Transpose[Partition[Flatten[Outer[List,{a,-a},{b,-b}]], 2]]>> (which generates {a+b,a-b,-a+b,-a-b}) ... only I'd like this to be> somehow done automatically for *each* combinatorial pair (and, for the> more general case when I generate combinatorial sets involving only> Ôk' elements). I've struggled with this for a while, and am only able> to generate such a list *manually* for each of my six original> combinatorial pairs ... a tedious, and somewhat tiresome procedure! :(> Is there a way of Ôeasily' doing this?!?>> With my newly generated list (having 4*6 Ôelements'), how can I also> go about finding which expressions involve/use only, say, 1 Minus? Is> there an Ôeasy' way of doing this too? (For instance, I'd like to> then Ôfilter' for (a-b) and (b-a) ...) (Perhaps the count of 1 Minus> is a little contrived for this example here, but for the more general> case I'll probably be considering, I might need to filter for, say,> (longer) expressions involving 2 Minuses (say).)>> feedback and help would be most welcome and appreciated!> Michael> ==== =There might be a better way to do this. But, here comes a method used by a newbie like me.Solve will give a list of solutions in form of {{a->1, b->2}, {a->2,b->3}}. This is a list, and you can use the normal way to access the element of list. Such as A={{a->1, b->2}, {a->2,b->3}}, then A[[1]] will give you {a->1, b->2}.And, A[[1]][[1]] will be a->1.Here a->1 is Rule[a,1], and you can use A[[1]][[1]][[1]] to get a, while A[[1]][[1]][[2]] to get 1.Try to read about the Principles of Mathematica in the Mathematica Book (in Help Browswer). That will help you to understand all these.Good luck.Liguo (Leo)>I am trying to reference the output of a Solve command which provided a list>of 5 solutions (looks like {a->1, b->2, etc.}).>>I would like to extract single answers from this result for use in a> > ==== =>I have had similar problems with Mathematica 4.2 on a new Apple G4,>running Mac OS 10.2.>>The crash sometimes happens when I am quitting Mathematica. It also>seems to be more likely when I am closing a notebook (file),>especially after several openings and closing of notebooks. But I>have also experienced crashes when trying to bring up the on-line>documentation.Occasionally, new versions of operating systems take us by surprise by introducing new conßicts, incompatibilities, or bugs while running Mathematica. That's what has happened here. MacOS X 10.2 causes several issues with the Mathematica user interface which did not occur in previous versions of MacOS X.Your crashing problem is the worst of them, but there are a couple of other serious ones. As somebody else pointed out few days ago, text copied from Cocoa applications (like Mail) does not paste correctly into Mathematica. This, also, is a problem newly introduced in 10.2.We're working on a patch right now, which will be freely available to anybody with a licensed copy of Mathematica 4.2 for MacOS X, and will fix all of the 10.2 issues we're aware of. I'll make an announcement on this forum when it's available.In the mean time, there is a workaround for the crashing problem. The most common occurrence of the crashing problem occurs as a result of using Command+D to press the Don't save button of the Do you want to save changes in this notebook dialog. Until the patch is available, you can avoid this particular cause of the crash by using the mouse to click the Don't save button instead.Sincerely,John Fultzjfultz@wolfram.comUser Interface GroupWolfram Research, Inc.Approved: Steven M. Christensen , ModeratorReply-To: spammers-go-here@yahoo.com ==== =I wish to do plot a vector field plot of an implicit solution.Equations :(*V[x] is a polynomial function defined earlier *)e[x_, v_] := 1/2 v^2 + V[x];t3 = Table[e[x, v] == e1, {e1, 0, 1, 0.2}];ImplicitPlot[Evaluate[t3], {x, (-2), 2}];This plots a nice implicit plot for various values of e1. What I wish to do is to attach a sense to the contours (an arrow that describes the direction of the orbit).However, I am at a loss as to how to do it with PlotVectorField.Any help would be appreciated.PS : Is there a way in which I can automate the labelling of the curves with the values of e1 they are plotted for (something better than manually editing the labels to the plot each time I change the range of e1) ?-- 3:29pm up 2:28, 1 user, load average: 0.07, 0.20, 0.16 ==== =I have no particular disagreements with anything in your interesting message. However, I do not see anything in it that, in my opinion, actually needs object oriented programming. In particular:> The> very statement that Ôa tensor is a geometric object which remains > invariant> under coordinate trasfromations' screams OOP to me.That's really just a matter of choosing how you think about these things. I prefer to think of tensors without any reference to coordinate transformations, they are just multi-linear mappings. That makes it extremely easy to define and manipulate tensors in Mathematica. No need here to think of objects. However, the situation becomes different when you want to consider tensor algebras as objects in a wider class of of objects, like graded algebras, which in turn are a subclass of an even wider class of algebras etc. For considering such kind of hierarchical structures OOP is very useful and that is why programs designed for this purpose, (like Macaulay II) adopt a very much OOP approach. In some sense of course OOP is the opposite of functional programming (particularly when combined with pattern matching). The former emphasizes data and their hierarchies while the latter concentrates on functions and their hierarchies. The two programming style are very different. (As a programmer I much prefer functional programming but as a user of a ready made program I often find OOP preferable). There are of course languages which contain both, would very much like to see a good OOP package for Mathematica, but I do not think I would like WRI to devote serious effort to develop such a functionality for Mathematica if it were to come at the expense of other things I am hoping to see in future versions.Andrzej KozlowskiYokohama, Japanhttp://www.mimuw.edu.pl/~akoz/http:// platon.c.u-tokyo.ac.jp/andrzej/>> Roman Maeder's package is meant for teaching computer science not for>> general use.>> I haven't studied his package in *any* detail. It's possible that a > lot of> what I /feel/ is missing, can be accomplished with a creative > combination of> Dr. Míóder's package, and careful use of contexts. Scoping, in > general, is a> subject which I have yet to get a grasp on in Mathematica. I had some > rather> strange name collisions while working with objects created from his > package.> It may have been the result of kernel clutter.>> Whether Mathematica would benefit from OO functionality>> has been a matter of some very heated debate, which you can find in>> this groups archives.>> Personally I am somewhere in the middle on this. I think it would be>> useful for developing packages for some very highly structured areas >> of>> mathematics (e.g. Algebraic Geometry). But for most applications in>> mathematics and physics the mixture of pattern based and functional>> programming offered by Mathematica is close to ideal and an additional>> programming paradigm would just get in the way. I don't think we need>> built in support for OOP in Mathematica but I am sure many would>> welcome a good AddOn package.>> I have to plead virtually complete ignorance on pattern based > programming. I> hope to read up on this topic soon. As far as objects and physics go. > The> very statement that Ôa tensor is a geometric object which remains > invariant> under coordinate trasfromations' screams OOP to me.>> I have already found Dr. Míóder's object paradigm useful in creating > something> I have wanted for quite some time. My creation is certainly not as > elegant> as I would like, but it works. I believe attempting the same thing > without> an OO framework would have been far more difficult for me. I'm sure > it can> be done, but I find OO helps me organize my thinking in a way that > cleanly> separates different parts of a problem space.>> (more or> less) evenly distributed point-like objects I called pixels. Each > pixel is> formed of four points. Each circle has a different color:> {1,0,0},{0,1,0},{0,0,1}. The circles are positioned relative to the > center> of the diagram at equal radial displacements, and angles 2Pi/4, 2Pi/4 +> 2Pi/3, 2Pi/4 + 2(2Pi/3) respectively.>> The points forming the pixel arranged such that one point is > positioned at the> location given for the entire pixel. The remaining points are > displaced a> small distance from the pixel location, at angles congruent to those > used to> position the circles. The point is given the color of the circle > sharing its> displacement direction, but only if the pixel location falls within the> circle, else it is set to {0,0,0}. The center point of the pixel is > given> the color representing the sum of the color vectors if its activated > pixels.>> In addition to all of the above, I created a filter mechanism which > takes a> three variable boolean predicate as an argument. The predicate is > used to> determine which pixels are actually added to the diagram.>> The result of all this is a Ven diagram tool which takes an arbitrary > logical> expression of three variables and produces the graphical > representation of> the expression. It may be usefull to add a fourth variable for the > Ôworld'.>> Most of the code lives in a class I called a ÔpointObj'. All other > objects in> the diagram are subclasses of pointObj. All of the mechanisms for> determining whether a point is in a circle, moving the object, adding > a point> to a pixel, creating the graphics primative, etc., are members of the> corresponding object. I have a mechanism to use either radial > coordinates,> or cartesian coordinates to position the object, or to query the > object for> its position. Of course I only need to maintain one pair of instance> variables to represent all four parameters since these are functionally> interdependant.>> The generalization of this system to three dimensions shold be trival. > I> already have a mechanism for determining the distance between two > points. I> can easily add an instance variable for mass, charge, velocity, etc to > the> pointObj class. Likewise, I can add member functions to determine the> Ôforces' contributed by all other objects in the diagram. It > sholdn't be> too hard to turn this whole diagram into a topologically closed > surface using> a wrap around where each edge is made functionally adjacent to its > opposite.> Of course, I will have to limit recursive inßuences at some point. > As a> first take, I could simply neglect all forces arrising from objects at > a> distance greater than the radius of the mathematical object bounded by > this> surface I have defined. That is, no object would produce a force felt > by> itself at a distance.>> In addition to all of the above, I could treat these objects as having > a> finite volume, and thus having rotational parameters in addition to > their> positional parameters. And the next obvious additon to the instance> variables after Euler angles, is ther derivative. Using a > generalization of> the afore mentioned pixel structure and assigning mass to each pixel> component, I could introduce concepts such as moment of inertia and > angular> momentum.>> The real fun begins when we realize that we have all the components of > the> momentum space as well as the configuration space. We could certainly> produce a corresponding diagram representing that space.>> I have the sense this would produce a better animation in something > like Java> 3D, but the design phases is probably going to be easier in > Mathematica. The> advantages that Java has are more complete OO support, and multi > threading.>> Now the one thing I haven't mentioned is the problem that there is no > such> thing as immediate action at a distance. Oh, and there is that other> question of the metric nature of the space represented by the diagram, > and> how the objects within the space affect that geometry. Introducing > special> relativity into this model should be fairly easy. We simply assume the> computer screen to be absolute rest, and use Lorenz transformations in > their> original sense.>> The real problem is running the animation in a finite period. So > after we get> objects, what we need is parallel computing to distribute the load.>> Hmmmm.>> Some day I'm going to have to actually finish a course in physics. At > least> one. Physics 101?> Andrzej Kozlowski>> Yokohama, Japan>> http://www.mimuw.edu.pl/~akoz/>> http://platon.c.u-tokyo.ac.jp/andrzej/>>> I must admit, Mathematica looks a lot different to me after having> done some> real programming in Java, than it did a few years ago. I understand> it much> better, but I also find myself grasping for things that don't seem to> be> native to the product/language.>> There seems to be virtually no native support for OOP in Mathematica.> Am I> understanding things correctly? Dr. M.95Ëüder (I'm being a bit stubborn> here -> use UTF-8) provides his own object package with his Computer Science> with> Mathematica. I haven't worked with yet, but by looking it over, it> seems a> bit kluged (> http://www.dict.org/bin/Dict?Form=Dict2&Database=*&Query= kluge> ). I don't mean to upbraid Dr. M.95Ëüder's attempt to add functionality> which> probably should be a native part of the Mathematica language. > Perhaps> I'll> get used to the approach he has used, but for now, I must say, it > seems> awkward. My guess is Dr. M.95Ëüder did the best that could be expected> with the> constraints under which he was working.>> It is inconceivable to me that I am the first person to question the> lack of> native OO support in Mathematica. There must be a history of> discussion on> this topic. Is anybody aware of a record of such? Am I not> understanding> things correctly? Do others believe OO support is lacking in> Mathematica,> and really Ôshould' be here?> --> STH> Hatton's Law:> There is only One inviolable Law.>> -- > STH> Hatton's Law:> There is only One inviolable Law.> ==== => First, suppose that I have 4 objects, a, b, c, and d, respectively.> How can I generate the permutation set when chosing, say, only *2*> elements.>> In[1]:= Permutations[{a,b,c,d}]>> gives me the permutation set when choosing *all* 4 objects ... :(In[1]:=<> Second, for the same four objects (a,b,c,d), to generate the> *combination* set (with 2 elements), I use:>> In[2]:= Needs[DiscreteMath`Combinatorica`];> In[3]:= cset=KSubsets[{a,b,c,d},2]>> and this generates the expected 6 combinatorial pairs> ({{a,b},{a,c},{a,d},{b,c},{b,d},{c,d}}).>> What I'd like to do next is add each combinatorial set, and I am able> to do this correctly via:>> In[4]:= Plus@@Transpose[cset]>> to obtain {a+b,a+c,a+d,b+c,b+d,c+d}.Alternatively:In[4]:=cset=KSubsets[ {a,b,c,d},2]Out[4]={{a,b},{a,c},{a,d},{b,c},{b,d},{c,d}}In[5] :=Plus@@@csetOut[5]={a+b,a+c,a+d,b+c,b+d,c+d}>> My problem lies in the fact that now, I'd like to be able to allow> *each* (a,b,c,d) element to be either plus, or minus (in reality, I'm> trying to generate combinatorial adds/minuses for *functions*> (a,b,c,d)), and to still generate the Ôsum' of the cominatorial set.> So for instance, in my current example, for the *first* {a,b}> combinatorial pair, I'd like to be able to generate>> In[5]:= > Plus@@Transpose[Partition[Flatten[Outer[List,{a,-a},{b,-b}]], 2]]>> (which generates {a+b,a-b,-a+b,-a-b}) ... only I'd like this to be> somehow done automatically for *each* combinatorial pair (and, for the> more general case when I generate combinatorial sets involving only> Ôk' elements). I've struggled with this for a while, and am only able> to generate such a list *manually* for each of my six original> combinatorial pairs ... a tedious, and somewhat tiresome procedure! :(> Is there a way of Ôeasily' doing this?!?For example:In[6]:=f[l_List,k_]:=Rest[Union[Plus@@@Perms[Join[l,- l],k]]]In[7]:=f[{a,b,c,d},2]Out[7]={-a-b,a-b,-a+b,a+b,-a-c, a-c,-b-c,b-c,-a+c,a+c,-b+c,b+c,-a-d,a-d,-b-d,b- d,- c-d,c-d,-a+d,a+d,-b+d,b+d,-c+d,c+d}>> With my newly generated list (having 4*6 Ôelements'), how can I also> go about finding which expressions involve/use only, say, 1 Minus? Is> there an Ôeasy' way of doing this too? (For instance, I'd like to> then Ôfilter' for (a-b) and (b-a) ...) (Perhaps the count of 1 Minus> is a little contrived for this example here, but for the more general> case I'll probably be considering, I might need to filter for, say,> (longer) expressions involving 2 Minuses (say).)In cases like the above the following will work:In[8]:=Count[#,-1,2]&/@%Out[8]={ 2,1,1,0,2,1,2,1,1,0,1,0,2,1,2,1,2,1,1,0,1,0,1,0}Andrzej KozlowskiYokohama, Japanhttp://www.mimuw.edu.pl/~akoz/http:// platon.c.u-tokyo.ac.jp/andrzej/Reply-To: rolf@mertig.com ==== =use WriteString:In[1]:= Do[ WriteString[stdout,i, ],{i,3}]1 2 3 --------Rolf MertigMertig Consultinghttp://www.mertig.comBerlin ==== =Madhusudan,I'm certain there is a way to obtain a nice plot for your function, butseverely limit your chances for a response.David Parkdjmp@earthlink.nethttp://home.earthlink.net/~djmp/orbit). However, I am at a loss as to how to do it with PlotVectorField.Any help would be appreciated.PS : Is there a way in which I can automate the labelling of the curveswith the valuesof e1 they are plotted for (something better than manually editing thelabels to the ploteach time I change the range of e1) ?--3:29pm up 2:28, 1 user, load average: 0.07, 0.20, 0.16Reply-To: spammers-get-bounced@yahoo.com ==== =On Friday 01 November 2002 21:18, David Park (djmp@earthlink.net) held forth in comp.soft-sys.math.mathematica ():> Madhusudan,> I'm certain there is a way to obtain a nice plot for your function, but> severely limit your chances for a response.> David Park> djmp@earthlink.net> http://home.earthlink.net/~djmp/> I wish to do plot a vector field plot of an implicit solution.> Equations :> (*V[x] is a polynomial function defined earlier *)> e[x_, v_] := 1/2 v^2 + V[x];> t3 = Table[e[x, v] == e1, {e1, 0, 1, 0.2}];> ImplicitPlot[Evaluate[t3], {x, (-2), 2}];> This plots a nice implicit plot for various values of e1. What I wish to do> is to attach a> sense to the contours (an arrow that describes the direction of the> orbit).> However, I am at a loss as to how to do it with PlotVectorField.> Any help would be appreciated.> PS : Is there a way in which I can automate the labelling of the curves> with the values> of e1 they are plotted for (something better than manually editing the> labels to the plot> each time I change the range of e1) ?> The example that I have quoted is the complete example. You may contact me at chhabra at eecs dot umich dot edu. ==== =I recently updated my notebook of Mathematica tips, tricks.You can download it from http://www.verbeia.com/mathematica/tips/Tricks.html or from ==== =I think your problem may be solved like this. I consider only the case with2 out of 4 elements. ThenIn[1]:=Needs[DiscreteMath`Combinatorica`];cset = KSubsets[{a, b, c, d}, 2]Out[2]={{a, b}, {a, c}, {a, d}, {b, c}, {b, d}, {c, d}}Define the function f (a simpler version of what you had already surmised):In[3]:=f[{x_, y_}] := Flatten[Outer[Plus, {-x, x}, {-y, y}]]so that, for example,In[4]:=f[a, b]Out[4]={-a - b, -a + b, a - b, a + b}Then, map f over cset and Flatten:In[5]:=newSet = Flatten[f /@ cset]Out[5]={-a - b, -a + b, a - b, a + b, -a - c, -a + c, a - c, a + c, -a - d, -a + d, a - d, a + d, -b - c, -b + c, b - c, b + c, -b - d, -b + d, b - d, b + d, -c - d, -c + d, c - d, c + d}You now get all the elements where the first term comes with a minus sign:In[6]:=Cases[newSet, -x_ + y_]Out[6]={-a - b, -a + b, a - b, -a - c, -a + c, a - c, -a - d, -a + d, a - d, -b - c, -b + c, b - c, -b - d, -b + d, b - d, -c - d, -c + d, c - d}and filter out those elements which have a second minus sign:In[7]:=DeleteCases[Cases[newSet, -x_ + y_], -x_ - y_]Out[7]={-a + b, a - b, -a + c, a - c, -a + d, a - d, -b + c, b - c, -b + d, b - d, -c + d, c - d}I guess this is what you were looking for. The logic may be extended tocover more general cases.Tomas GarzaMexico City----- Original Message -----> elements.>> In[1]:= Permutations[{a,b,c,d}]>> gives me the permutation set when choosing *all* 4 objects ... :(>> Second, for the same four objects (a,b,c,d), to generate the> *combination* set (with 2 elements), I use:>> In[2]:= Needs[DiscreteMath`Combinatorica`];> In[3]:= cset=KSubsets[{a,b,c,d},2]>> and this generates the expected 6 combinatorial pairs> ({{a,b},{a,c},{a,d},{b,c},{b,d},{c,d}}).>> What I'd like to do next is add each combinatorial set, and I am able> to do this correctly via:>> In[4]:= Plus@@Transpose[cset]>> to obtain {a+b,a+c,a+d,b+c,b+d,c+d}.>> My problem lies in the fact that now, I'd like to be able to allow> *each* (a,b,c,d) element to be either plus, or minus (in reality, I'm> trying to generate combinatorial adds/minuses for *functions*> (a,b,c,d)), and to still generate the Ôsum' of the cominatorial set.> So for instance, in my current example, for the *first* {a,b}> combinatorial pair, I'd like to be able to generate>> In[5]:= Plus@@Transpose[Partition[Flatten[Outer[List,{a,-a},{b,-b}]], 2]]>> (which generates {a+b,a-b,-a+b,-a-b}) ... only I'd like this to be> somehow done automatically for *each* combinatorial pair (and, for the> more general case when I generate combinatorial sets involving only> Ôk' elements). I've struggled with this for a while, and am only able> to generate such a list *manually* for each of my six original> combinatorial pairs ... a tedious, and somewhat tiresome procedure! :(> Is there a way of Ôeasily' doing this?!?>> With my newly generated list (having 4*6 Ôelements'), how can I also> go about finding which expressions involve/use only, say, 1 Minus? Is> there an Ôeasy' way of doing this too? (For instance, I'd like to> then Ôfilter' for (a-b) and (b-a) ...) (Perhaps the count of 1 Minus> is a little contrived for this example here, but for the more general> case I'll probably be considering, I might need to filter for, say,> (longer) expressions involving 2 Minuses (say).)>> feedback and help would be most welcome and appreciated!> Michael>> ==== =I guess I did not exactly answer your last question. To select those expressions that involve just one minus use:l={-a-b,a-b,-a+b,a+b,-a-c,a-c,-b-c,b-c,-a+c,a+c,-b+c,b+c, -a-d,a-d,-b- d,b-d,-c- d,c-d,-a+d,a+d,-b+d,b+d,-c+d,c+d};Select[l,Count[#,-1,2]==1&] {a-b,-a+b,a-c,b-c,-a+c,-b+c,a-d,b-d,c-d,-a+d,-b+d,-c+d}>> First, suppose that I have 4 objects, a, b, c, and d, respectively.>> How can I generate the permutation set when chosing, say, only *2*>> elements.>> In[1]:= Permutations[{a,b,c,d}]>> gives me the permutation set when choosing *all* 4 objects ... :(> In[1]:=> <> In[2]:=> Perms[l_List,k_]:=Flatten[Permutations/@KSubsets[l,k],1]>> In[3]:=> Perms[{a,b,c,d},2]>> Out[3]=> {{a,b},{b,a},{a,c},{c,a},{a,d},{d,a},{a,e},{e,a},{b,c},{c,b}, {b,d},{d,b > },{> b,e},{e,b},{c,d},{d,c},{c,e},{e,c},{d,e},{e,d}}>>> Second, for the same four objects (a,b,c,d), to generate the>> *combination* set (with 2 elements), I use:>> In[2]:= Needs[DiscreteMath`Combinatorica`];>> In[3]:= cset=KSubsets[{a,b,c,d},2]>> and this generates the expected 6 combinatorial pairs>> ({{a,b},{a,c},{a,d},{b,c},{b,d},{c,d}}).>> What I'd like to do next is add each combinatorial set, and I am able>> to do this correctly via:>> In[4]:= Plus@@Transpose[cset]>> to obtain {a+b,a+c,a+d,b+c,b+d,c+d}.>> Alternatively:>> In[4]:=> cset=KSubsets[{a,b,c,d},2]> Out[4]=> {{a,b},{a,c},{a,d},{b,c},{b,d},{c,d}}>> In[5]:=> Plus@@@cset>> Out[5]=> {a+b,a+c,a+d,b+c,b+d,c+d}>>> My problem lies in the fact that now, I'd like to be able to allow>> *each* (a,b,c,d) element to be either plus, or minus (in reality, I'm>> trying to generate combinatorial adds/minuses for *functions*>> (a,b,c,d)), and to still generate the Ôsum' of the cominatorial set.>> So for instance, in my current example, for the *first* {a,b}>> combinatorial pair, I'd like to be able to generate>> In[5]:= >> Plus@@Transpose[Partition[Flatten[Outer[List,{a,-a},{b,-b}]], 2]]>> (which generates {a+b,a-b,-a+b,-a-b}) ... only I'd like this to be>> somehow done automatically for *each* combinatorial pair (and, for the>> more general case when I generate combinatorial sets involving only>> Ôk' elements). I've struggled with this for a while, and am only able>> to generate such a list *manually* for each of my six original>> combinatorial pairs ... a tedious, and somewhat tiresome procedure! :(>> Is there a way of Ôeasily' doing this?!?>> For example:>> In[6]:=> f[l_List,k_]:=Rest[Union[Plus@@@Perms[Join[l,-l],k]]]>> In[7]:=> f[{a,b,c,d},2]>> Out[7]=> {-a-b,a-b,-a+b,a+b,-a-c,a-c,-b-c,b-c,-a+c,a+c,-b+c,b+c,-a-d, a-d,-b- > d,b-d,-> c-d,c-d,-a+d,a+d,-b+d,b+d,-c+d,c+d}>>> With my newly generated list (having 4*6 Ôelements'), how can I also>> go about finding which expressions involve/use only, say, 1 Minus? Is>> there an Ôeasy' way of doing this too? (For instance, I'd like to>> then Ôfilter' for (a-b) and (b-a) ...) (Perhaps the count of 1 Minus>> is a little contrived for this example here, but for the more general>> case I'll probably be considering, I might need to filter for, say,>> (longer) expressions involving 2 Minuses (say).)> In cases like the above the following will work:>> In[8]:=> Count[#,-1,2]&/@%>> Out[8]=> {2,1,1,0,2,1,2,1,1,0,1,0,2,1,2,1,2,1,1,0,1,0,1,0}>> Andrzej Kozlowski> Yokohama, Japan> http://www.mimuw.edu.pl/~akoz/> http://platon.c.u-tokyo.ac.jp/andrzej/>>Andrzej KozlowskiYokohama, Japanhttp://www.mimuw.edu.pl/~akoz/http:// platon.c.u-tokyo.ac.jp/andrzej/ ==== =In a sense this problem gives me an excuse to call attention to one of the best uses I've seen a computer put to. The figure-8 Animation in David Park's DrawGraphics package is exactly the kind of graphical expression of the mathematics of physics which reviel more about the situation than pencile and paper lend themselves to. (People such as John A. Wheeler, and Hermann Weyl seem to have this kind of mechanism build into thier brains, and therefore don't need no stinkin' computer.)While I was exploring this animation I noticed something rather strange about the CPU's behavior. If I open Help Browser -> Add-Ons -> DrawGraphics -> Examples -> Figure Eight Animation, the CPU utilization is virtually 0.I evaluate the first cell to load the package and the CPU jumps for a second and then settles back down. I then select the remainder of the notebook. The CPU utilization remains very low. Then I evaluate it. The CPU utilization jumps way up, as is to be expected. The animation frames are created, and the animation runs fine. The CPU utilization remains very high.The interesting observation comes when I stop the animation by quitting the local kernel. If I select the cell holding the graphic, I notice the CPU utilization jups to 98%+-. The kernel isn't even running at this time. When I say I select the cell holding the graphic, I mean to say I select the brace to the right which has the Ôfoldable' indicator. Selecting the inner-most brace does not cause the CPU utilization to increase, but selecting any of its parents does.Can someone explain this?You can find the DrawGraphics package here:http://home.earthlink.net/~djmp/Mathematica.html-- STHHatton's Law: There is only One inviolable Law. ==== => I have no particular disagreements with anything in your interesting> message. However, I do not see anything in it that, in my opinion,>> actually needs sealed in an air-tight Ôcoffin' for several hours with a candle burning next to him. He survived, and IIRC, the candle was still burning. *Need* is a relative statement. ;-)> object oriented programming. In particular:> The> very statement that Ôa tensor is a geometric object which remains> invariant> under coordinate trasfromations' screams OOP to me.>> That's really just a matter of choosing how you think about these> things. I prefer to think of tensors without any reference to> coordinate transformations, they are just multi-linear mappings. Multi-linear mappings of what? I mistated the definition a bit. I should have said that a tensor is a geometric object independent of any particular coordinate system. The fact that it's invariant under coordinate transformations, is a result of this refined definition. Nonetheless, the concept of a tensor completely void of all coordinate systems is, to me, the sound of one hand clapping.> That> makes it extremely easy to define and manipulate tensors in> Mathematica. No need here to think of objects.I believe this depends on what you are doing with the tensor. To soe extent, I might agree with you. I believe a philosophical analysis would demonstrate that the non-objective concept of a tensor is just a case of form defining contour. I'm interested in the geometric nature of tensors, and more specifically, in the geometric nature of the objects which tensors describe.> However, the situation> becomes different when you want to consider tensor algebras as objects> in a wider class of of objects, like graded algebras, which in turn are> a subclass of an even wider class of algebras etc. For considering such> kind of hierarchical structures OOP is very useful and that is why> programs designed for this purpose, (like Macaulay II) adopt a very> much OOP approach.This is a bit beyond my current understanding, but it sounds to me that you are focusing on the algegraic nature of tensors. That's certainly an interesting area, and for your purposes, objects may not be beneficial.> In some sense of course OOP is the opposite of> functional programming (particularly when combined with pattern> matching). The former emphasizes data and their hierarchies while the> latter concentrates on functions and their hierarchies. The two> programming style are very different.Then of course, we have the possible view that functions are objects, which seems to contradict the view that these are conßicting approaches.> (As a programmer I much prefer> functional programming but as a user of a ready made program I often> find OOP preferable). There are of course languages which contain both,> such as object oriented versions of Common Lisp.I read about this stuff many, many, many years ago. FLOOP means Functional List Object Oriented Programming. See _Goedel, Escher, Bach_, by Hofstadter, 1979. I wasn't a programmer then, and my understanding of the topic bordered on the mythical, at the time. I would really need to review the subject before I could confidently address this.> would very much like to see a good OOP package for Mathematica, but I> do not think I would like WRI to devote serious effort to develop such> a functionality for Mathematica if it were to come at the expense of> other things I am hoping to see in future versions.A place I believe OOP would naturally benefit Mathematica is in the area of XML and particularly implementing the DOM IDL. There seem to be some problems with Mathematica's XML implementation. I suspect a good OOP approach might help in preventing some of these problems in the future. As name.> Andrzej Kozlowski> Yokohama, Japan> http://www.mimuw.edu.pl/~akoz/> http://platon.c.u-tokyo.ac.jp/andrzej/> Roman Maeder's package is meant for teaching computer science not for>> general use.>> I haven't studied his package in *any* detail. It's possible that a> lot of> what I /feel/ is missing, can be accomplished with a creative> combination of> Dr. Míóder's package, and careful use of contexts. Scoping, in> general, is a> subject which I have yet to get a grasp on in Mathematica. I had some> rather> strange name collisions while working with objects created from his> package.> It may have been the result of kernel clutter.> Whether Mathematica would benefit from OO functionality>> has been a matter of some very heated debate, which you can find in>> this groups archives.>> Personally I am somewhere in the middle on this. I think it would be>> useful for developing packages for some very highly structured areas>> of>> mathematics (e.g. Algebraic Geometry). But for most applications in>> mathematics and physics the mixture of pattern based and functional>> programming offered by Mathematica is close to ideal and an additional>> programming paradigm would just get in the way. I don't think we need>> built in support for OOP in Mathematica but I am sure many would>> welcome a good AddOn package.>> I have to plead virtually complete ignorance on pattern based> programming. I> hope to read up on this topic soon. As far as objects and physics go.> The> very statement that Ôa tensor is a geometric object which remains> invariant> under coordinate trasfromations' screams OOP to me.>> I have already found Dr. Míóder's object paradigm useful in creating> something> I have wanted for quite some time. My creation is certainly not as> elegant> as I would like, but it works. I believe attempting the same thing> without> an OO framework would have been far more difficult for me. I'm sure> it can> be done, but I find OO helps me organize my thinking in a way that> cleanly> separates different parts of a problem space.>> (more or> less) evenly distributed point-like objects I called pixels. Each> pixel is> formed of four points. Each circle has a different color:> {1,0,0},{0,1,0},{0,0,1}. The circles are positioned relative to the> center> of the diagram at equal radial displacements, and angles 2Pi/4, 2Pi/4 +> 2Pi/3, 2Pi/4 + 2(2Pi/3) respectively.>> The points forming the pixel arranged such that one point is> positioned at the> location given for the entire pixel. The remaining points are> displaced a> small distance from the pixel location, at angles congruent to those> used to> position the circles. The point is given the color of the circle> sharing its> displacement direction, but only if the pixel location falls within the> circle, else it is set to {0,0,0}. The center point of the pixel is> given> the color representing the sum of the color vectors if its activated> pixels.>> In addition to all of the above, I created a filter mechanism which> takes a> three variable boolean predicate as an argument. The predicate is> used to> determine which pixels are actually added to the diagram.>> The result of all this is a Ven diagram tool which takes an arbitrary> logical> expression of three variables and produces the graphical> representation of> the expression. It may be usefull to add a fourth variable for the> Ôworld'.>> Most of the code lives in a class I called a ÔpointObj'. All other> objects in> the diagram are subclasses of pointObj. All of the mechanisms for> determining whether a point is in a circle, moving the object, adding> a point> to a pixel, creating the graphics primative, etc., are members of the> corresponding object. I have a mechanism to use either radial> coordinates,> or cartesian coordinates to position the object, or to query the> object for> its position. Of course I only need to maintain one pair of instance> variables to represent all four parameters since these are functionally> interdependant.>> The generalization of this system to three dimensions shold be trival.> I> already have a mechanism for determining the distance between two> points. I> can easily add an instance variable for mass, charge, velocity, etc to> the> pointObj class. Likewise, I can add member functions to determine the> Ôforces' contributed by all other objects in the diagram. It> sholdn't be> too hard to turn this whole diagram into a topologically closed> surface using> a wrap around where each edge is made functionally adjacent to its> opposite.> Of course, I will have to limit recursive inßuences at some point.> As a> first take, I could simply neglect all forces arrising from objects at> a> distance greater than the radius of the mathematical object bounded by> this> surface I have defined. That is, no object would produce a force felt> by> itself at a distance.>> In addition to all of the above, I could treat these objects as having> a> finite volume, and thus having rotational parameters in addition to> their> positional parameters. And the next obvious additon to the instance> variables after Euler angles, is ther derivative. Using a> generalization of> the afore mentioned pixel structure and assigning mass to each pixel> component, I could introduce concepts such as moment of inertia and> angular> momentum.>> The real fun begins when we realize that we have all the components of> the> momentum space as well as the configuration space. We could certainly> produce a corresponding diagram representing that space.>> I have the sense this would produce a better animation in something> like Java> 3D, but the design phases is probably going to be easier in> Mathematica. The> advantages that Java has are more complete OO support, and multi> threading.>> Now the one thing I haven't mentioned is the problem that there is no> such> thing as immediate action at a distance. Oh, and there is that other> question of the metric nature of the space represented by the diagram,> and> how the objects within the space affect that geometry. Introducing> special> relativity into this model should be fairly easy. We simply assume the> computer screen to be absolute rest, and use Lorenz transformations in> their> original sense.>> The real problem is running the animation in a finite period. So> after we get> objects, what we need is parallel computing to distribute the load.>> Hmmmm.>> Some day I'm going to have to actually finish a course in physics. At> least> one. Physics 101?> Andrzej Kozlowski>> Yokohama, Japan>> http://www.mimuw.edu.pl/~akoz/>> http://platon.c.u-tokyo.ac.jp/andrzej/>>> I must admit, Mathematica looks a lot different to me after having> done some> real programming in Java, than it did a few years ago. I understand> it much> better, but I also find myself grasping for things that don't seem to> be> native to the product/language.>> There seems to be virtually no native support for OOP in Mathematica.> Am I> understanding things correctly? Dr. M.95Ëüder (I'm being a bit stubborn> here -> use UTF-8) provides his own object package with his Computer Science> with> Mathematica. I haven't worked with yet, but by looking it over, it> seems a> bit kluged (> http://www.dict.org/bin/Dict?Form=Dict2&Database=*&Query= kluge> ). I don't mean to upbraid Dr. M.95Ëüder's attempt to add functionality> which> probably should be a native part of the Mathematica language.> Perhaps> I'll> get used to the approach he has used, but for now, I must say, it> seems> awkward. My guess is Dr. M.95Ëüder did the best that could be expected> with the> constraints under which he was working.>> It is inconceivable to me that I am the first person to question the> lack of> native OO support in Mathematica. There must be a history of> discussion on> this topic. Is anybody aware of a record of such? Am I not> understanding> things correctly? Do others believe OO support is lacking in> Mathematica,> and really Ôshould' be here?> --> STH> Hatton's Law:> There is only One inviolable Law.>> --> STH> Hatton's Law:> There is only One inviolable Law.-- STHHatton's Law: There is only One inviolable Law. ==== => Roman Maeder's package is meant for teaching computer science not for> general use. I haven't studied his package in *any* detail. It's possible that a lot of what I /feel/ is missing, can be accomplished with a creative combination of Dr. Míóder's package, and careful use of contexts. Scoping, in general, is a subject which I have yet to get a grasp on in Mathematica. I had some rather strange name collisions while working with objects created from his package. It may have been the result of kernel clutter.>Whether Mathematica would benefit from OO functionality> has been a matter of some very heated debate, which you can find in> this groups archives.> Personally I am somewhere in the middle on this. I think it would be> useful for developing packages for some very highly structured areas of> mathematics (e.g. Algebraic Geometry). But for most applications in> mathematics and physics the mixture of pattern based and functional> programming offered by Mathematica is close to ideal and an additional> programming paradigm would just get in the way. I don't think we need> built in support for OOP in Mathematica but I am sure many would> welcome a good AddOn package.I have to plead virtually complete ignorance on pattern based programming. I hope to read up on this topic soon. As far as objects and physics go. The very statement that Ôa tensor is a geometric object which remains invariant under coordinate trasfromations' screams OOP to me.I have already found Dr. Míóder's object paradigm useful in creating something I have wanted for quite some time. My creation is certainly not as elegant as I would like, but it works. I believe attempting the same thing without an OO framework would have been far more difficult for me. I'm sure it can be done, but I find OO helps me organize my thinking in a way that cleanly separates different parts of a problem space.less) evenly distributed point-like objects I called pixels. Each pixel is formed of four points. Each circle has a different color: {1,0,0},{0,1,0},{0,0,1}. The circles are positioned relative to the center of the diagram at equal radial displacements, and angles 2Pi/4, 2Pi/4 + 2Pi/3, 2Pi/4 + 2(2Pi/3) respectively.The points forming the pixel arranged such that one point is positioned at the location given for the entire pixel. The remaining points are displaced a small distance from the pixel location, at angles congruent to those used to position the circles. The point is given the color of the circle sharing its displacement direction, but only if the pixel location falls within the circle, else it is set to {0,0,0}. The center point of the pixel is given the color representing the sum of the color vectors if its activated pixels.In addition to all of the above, I created a filter mechanism which takes a three variable boolean predicate as an argument. The predicate is used to determine which pixels are actually added to the diagram.The result of all this is a Ven diagram tool which takes an arbitrary logical expression of three variables and produces the graphical representation of the expression. It may be usefull to add a fourth variable for the Ôworld'.Most of the code lives in a class I called a ÔpointObj'. All other objects in the diagram are subclasses of pointObj. All of the mechanisms for determining whether a point is in a circle, moving the object, adding a point to a pixel, creating the graphics primative, etc., are members of the corresponding object. I have a mechanism to use either radial coordinates, or cartesian coordinates to position the object, or to query the object for its position. Of course I only need to maintain one pair of instance variables to represent all four parameters since these are functionally interdependant.The generalization of this system to three dimensions shold be trival. I already have a mechanism for determining the distance between two points. I can easily add an instance variable for mass, charge, velocity, etc to the pointObj class. Likewise, I can add member functions to determine the Ôforces' contributed by all other objects in the diagram. It sholdn't be too hard to turn this whole diagram into a topologically closed surface using a wrap around where each edge is made functionally adjacent to its opposite. Of course, I will have to limit recursive inßuences at some point. As a first take, I could simply neglect all forces arrising from objects at a distance greater than the radius of the mathematical object bounded by this surface I have defined. That is, no object would produce a force felt by itself at a distance.In addition to all of the above, I could treat these objects as having a finite volume, and thus having rotational parameters in addition to their positional parameters. And the next obvious additon to the instance variables after Euler angles, is ther derivative. Using a generalization of the afore mentioned pixel structure and assigning mass to each pixel component, I could introduce concepts such as moment of inertia and angular momentum. The real fun begins when we realize that we have all the components of the momentum space as well as the configuration space. We could certainly produce a corresponding diagram representing that space.I have the sense this would produce a better animation in something like Java 3D, but the design phases is probably going to be easier in Mathematica. The advantages that Java has are more complete OO support, and multi threading.Now the one thing I haven't mentioned is the problem that there is no such thing as immediate action at a distance. Oh, and there is that other question of the metric nature of the space represented by the diagram, and how the objects within the space affect that geometry. Introducing special relativity into this model should be fairly easy. We simply assume the computer screen to be absolute rest, and use Lorenz transformations in their original sense. The real problem is running the animation in a finite period. So after we get objects, what we need is parallel computing to distribute the load.Hmmmm.Some day I'm going to have to actually finish a course in physics. At least one. Physics 101?> Andrzej Kozlowski> Yokohama, Japan> http://www.mimuw.edu.pl/~akoz/> http://platon.c.u-tokyo.ac.jp/andrzej/>> I must admit, Mathematica looks a lot different to me after having> done some> real programming in Java, than it did a few years ago. I understand> it much> better, but I also find myself grasping for things that don't seem to> be> native to the product/language.>> There seems to be virtually no native support for OOP in Mathematica.> Am I> understanding things correctly? Dr. M.95Ëüder (I'm being a bit stubborn> here -> use UTF-8) provides his own object package with his Computer Science> with> Mathematica. I haven't worked with yet, but by looking it over, it> seems a> bit kluged (> http://www.dict.org/bin/Dict?Form=Dict2&Database=*&Query= kluge> ). I don't mean to upbraid Dr. M.95Ëüder's attempt to add functionality> which> probably should be a native part of the Mathematica language. Perhaps> I'll> get used to the approach he has used, but for now, I must say, it seems> awkward. My guess is Dr. M.95Ëüder did the best that could be expected> with the> constraints under which he was working.>> It is inconceivable to me that I am the first person to question the> lack of> native OO support in Mathematica. There must be a history of> discussion on> this topic. Is anybody aware of a record of such? Am I not> understanding> things correctly? Do others believe OO support is lacking in> Mathematica,> and really Ôshould' be here?> --> STH> Hatton's Law:> There is only One inviolable Law.-- STHHatton's Law: There is only One inviolable Law. ==== =Steven Hatton was wondering about OOP support in Mathematica. You are correct in that Mathematica doesn't have built-in support of OOP. Ialso don't care much for Dr. Maeder's OOP package. However, I am only abeginner with OOP, so my assessment may not be accurate. If you are going to become proficient with Mathematica you need to let go ofyour OOP way of doing things, and learn the Mathematica way. Mathematicaactually has a beautiful and powerful language, but you need to learn how touse it. I give some useful examples below. What would be needed to dothese things in another language or some other math software?----------Here I find all {x,y} pairs with (y>5) and return {x, y, x^2+y^2}. Noticethe mixed data types.In[1]:=data={{12,2},{3,4},{2,2 Pi},{7,13.4},{3,22},{11,2},{10,9},{6,9.3}};Cases[data,{x_,y_} /;y>5:>{x,y,Sqrt[x^2+y^2]}]Out[2]={{2, 2*Pi, Sqrt[4 + 4*Pi^2]}, {7, 13.4, 15.1182}, {3, 22, Sqrt[493]}, {10,9, Sqrt[181]}, {6, 9.3, 11.0675}}---------Next I define a function that takes any numeric value. Here (z) has no numeric value so f[z] is undefined. Again notice the mixeddata types.In[3]:=f[x_?NumericQ]:=x^2+1;f/@{z,3,2Pi,4.5,2+3I}Out[4] = {f[z], 10, 1 + 4*Pi^2, 21.25, -4 + 12*I}--------------Mathematica has a rich set of functions that let you perform various usefuloperations. Here I take a long list and break it into a set of smaller lists. We canget many variations of this by giving Partition other arguments.In[5]:=lst={1,2Pi,3+x,4,5,6-x,7,8x, 9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29, 30};Partition[lst,4,3]Out[6]={ {1, 2*Pi, 3 + x, 4}, {4, 5, 6 - x, 7}, {7, 8*x, 9, 10}, {10, 11, 12, 13},{13, 14, 15, 16}, {16, 17, 18, 19}, {19, 20, 21, 22}, {22, 23, 24, 25}, {25, 26, 27, 28}}--------------In addition to the examples above - Mathematica has a tremendous amount of mathematical knowledge built-in. - With Mathematica doing and calculations with high precision is trivial. - With Mathematica calculations involving integers with thousands, ormillions of digits is trivial.--------- Ted ErsekDownload my latest Mathematica Tips, Tricks from http://www.verbeia.com/mathematica/tips/Tricks.html or from ==== =I am new to mathematica, but I would like to symbolicaly convolve two impulse sequences ... both sequences use different sampling techniqueshere is what I have so far ...impulseTrain1[_t] := DiracDelta[f - t]impulseTrain2[_t] := DiracDelta[f - 10^t]I would like the variable Ôt' to be discrete and a natural number.I would like to convolve impulseTrain1 and impulseTrain2. I would like the result to still be symbolic ... is it possible ??thanksMatt-- http://mffm.darktech.orgWSOLA TimeScale Audio Mod : http://mffmtimescale.sourceforge.net/FFTw C++ : http://mffmfftwrapper.sourceforge.net/Vector Bass : http://mffmvectorbass.sourceforge.net/Multimedia Time Code : http://mffmtimecode.sourceforge.net/Reply-To: ctgarric@edisto.cofc.edu ==== =I have two questions:First: I have created several files of 3D scatterplots from listsimported from text files. It looks like this:<< Graphics`Graphics3D`SetDirectory[c:Documents and SettingschrisMy Documentsmathxyeke]Directory[]data = ReadList[33.txt, Number, RecordLists -> True];ScatterPlot3D[data, PlotRange -> {0, 2}, BoxRatios -> {1, 1, 1.5}, ViewPoint -> {1, .1, -.1}, Boxed -> False, AxesEdge -> {{1, -1}, {1, -1}, {-1, 1}}]I would like to create a surface plot with this data as well, I foundsome discussion in the archives, but could not find any answers on how to do this. ListSurfacePlot does not seem to work, I believe that isbecause the points are not uniformly spaced in the x-y plane. Anyhelp on how to do this would be great.Second: I have taken these plots and put them in a single program bycopy/paste so that Mathematica can animate them. I am having a hard time exporting these graphics as a animation into a .gif file. The problem is that i cannot define the cells as a graphic expression that Mathematica will convert. I gat create .gifs of individual images from the originalfiles, but cannot create the .gif for the animation. Can someone give me a few pointer?ctgarric@edisto.cofc.eduReply-To: kuska@informatik.uni-leipzig.de ==== =look what TriangularSurfacePlot[] form< I have two questions:> First: I have created several files of 3D scatterplots from lists> imported from text files. It looks like this:> << Graphics`Graphics3D`> SetDirectory[c:Documents and SettingschrisMy Documentsmathxyeke]> Directory[]> data = ReadList[33.txt, Number, RecordLists -> True];> ScatterPlot3D[data, PlotRange -> {0, 2}, BoxRatios -> {1, 1, 1.5},> ViewPoint -> {1, .1, -.1}, Boxed -> False,> AxesEdge -> {{1, -1}, {1, -1}, {-1, 1}}]> I would like to create a surface plot with this data as well, I found> some discussion in the archives, but could not find any answers on how to> do this. ListSurfacePlot does not seem to work, I believe that is> because the points are not uniformly spaced in the x-y plane. Anyhelp on> how to do this would be great.> Second: I have taken these plots and put them in a single program by> copy/paste so that Mathematica can animate them. I am having a hard time> exporting these graphics as a animation into a .gif file. The problem is> that i cannot define the cells as a graphic expression that Mathematica> will convert. I gat create .gifs of individual images from the original> files, but cannot create the .gif for the animation. Can someone give me> a few pointer?> ctgarric@edisto.cofc.edu ==== => object oriented programming. In particular:> The> very statement that Ôa tensor is a geometric object which remains> invariant> under coordinate trasfromations' screams OOP to me.>> That's really just a matter of choosing how you think about these>> things. I prefer to think of tensors without any reference to>> coordinate transformations, they are just multi-linear mappings.>> Multi-linear mappings of what? I mistated the definition a bit. I > should> have said that a tensor is a geometric object independent of any > particular> coordinate system. The fact that it's invariant under coordinate> transformations, is a result of this refined definition. Nonetheless, > the> concept of a tensor completely void of all coordinate systems is, to > me, the> sound of one hand clapping.The concept of a vector space needs no mention of any coordinate systems. Neither does the concept of a manifold, its tangent bundle or a tensor (a section of the bundle of tensors). Coordinates are obviously useful for doing computations but not the best way to define or think about the concepts (or prove theorems). However, this is rather far from Mathematica and OOP.> However, the situation>> becomes different when you want to consider tensor algebras as objects>> in a wider class of of objects, like graded algebras, which in turn >> are>> a subclass of an even wider class of algebras etc. For considering >> such>> kind of hierarchical structures OOP is very useful and that is why>> programs designed for this purpose, (like Macaulay II) adopt a very>> much OOP approach.>> This is a bit beyond my current understanding, but it sounds to me > that you> are focusing on the algegraic nature of tensors. That's certainly an> interesting area, and for your purposes, objects may not be beneficial.I think it's the other way round. OOP is beneficial when you have a lot of hierarchical structure, so that you want elements of substructures to automatically inherit the properties of higher structures, etc. This is the main reason why specialized programs like Macaulay II, which is intended for the study of such hierarchical structures in Algebraic Geometry, tend to be very OO. By contrast Mathematica leaves the structures you are dealing with implicit. In Macauly II a symbol like x is always an element of some structure (usually some kind of ring) but in Mathematica its just a symbol. What counts is the functions that you define. Both approaches have their advantages, but for a *general purpose* science and mathematics program the Mathematica approach seems the right one to me.>> A place I believe OOP would naturally benefit Mathematica is in the > area of> XML and particularly implementing the DOM IDL. There seem to be some> problems with Mathematica's XML implementation. I suspect a good OOP> approach might help in preventing some of these problems in the > future. As> middle> name.Since I know absolutely nothing about this I will diplomatically agree. But I am now sure if this XML business is really related to the Mathematica programming language?AndrzejAndrzej KozlowskiYokohama, Japanhttp://www.mimuw.edu.pl/~akoz/http:// platon.c.u-tokyo.ac.jp/andrzej/ ==== =There is a tendency to see a contrast between OO and Mathematica. In myopinion this makes no sense:OO descibes a method for structuring programs and the data related to theprograms. Mathemtica describes the instructions with which programs may bebuilt.Hermann Schmitt ==== =are there any tools to do numerical experiments in chaotical systems with?some package that will accelerate computing, some book helping to programthis? thx._________________________________________________________ _________ ckkm_________________________________________________________ _________ ==== =http://groups.yahoo.com/group/CommAlg/This group is for people who are interested in commutative algebra.Please join the group. I welcome to your participation.Peyman Nasehpour ==== =This may be a stupid question but is there an easy way to importcomplex numbers from a file into mathematica. I have written some c++code that outputs a set of complex numbers to a file and I have beentrying to get them into mathematica. What format should I use?To give myself a clue I exported a couple of complex numbers fromMathematica to see what the file would look like:Export[test.dat, {3 + 2 I, 1 + 0.5 I}, List];which gives me the following test.dat:3 + 2 I1 + 0.5 Iso far so good - looks like thats the format I need my c++ code tooutput but when i trytest = Import[test.dat, List];i get the following outputtest = {3, +, 2, I, 1, +, 0.5, I}Can anyone help me? I want to be able to Import the file directly - Iwould rather not simply import a big list of numbers and write afunction that makes the relavent ones complex. Any help would be muchappreciatedMikeReply-To: kuska@informatik.uni-leipzig.de ==== =and ReadList[test.dat]does what you want. Jens> This may be a stupid question but is there an easy way to import> complex numbers from a file into mathematica. I have written some c++> code that outputs a set of complex numbers to a file and I have been> trying to get them into mathematica. What format should I use?> To give myself a clue I exported a couple of complex numbers from> Mathematica to see what the file would look like:> Export[test.dat, {3 + 2 I, 1 + 0.5 I}, List];> which gives me the following test.dat:> 3 + 2 I> 1 + 0.5 I> so far so good - looks like thats the format I need my c++ code to> output but when i try> test = Import[test.dat, List];> i get the following output> test = {3, +, 2, I, 1, +, 0.5, I}> Can anyone help me? I want to be able to Import the file directly - I> would rather not simply import a big list of numbers and write a> function that makes the relavent ones complex. Any help would be much> appreciated> Mike ==== =There are some problems with the Meaningful Solution*In response to the first argument:Yes it is true that any number multiplied by zero is zero, infinity isnot truly a number so that rule does not apply. The rules of +,-,*,/do not apply to infinity like they do to numbers (infinity+1=infinity, infinity*2=infinity etc.). Therefore it cannot be saidthat infinity*0=0 (infinity * anything =infinity, but likewiseanything * 0= 0 we encounter a contradiction for inf*0)*In response to the second argument:The claim is that 100/100=1, this is true. Now he claims that youcancel off the zeros (0/0) of the ones place which results in 10/10followed by the zeros of the tens place resulting in 1/1=1. That isnot what is happening. Using that same method to divide 25/125 we cancancel off the 5/5 leaving us with 2/12 =1/6 where 25/125=1/5 (1/6 notequal to 1/5). There is obviously something wrong with that method ofcancellation (the problem is that he would cancel the 5s fromThis is what really happens:100/100=(10*10)/(10*10) =(10/10)*(10/10) =1*(10/10) =10/10 =1Likewise: 25/125=(5*5)/(5*25) =(5/5)*(5/25) =1*(5/25) =5/25 =5/(5*5) =(5/5)*(1/5) =1*(1/5) =1/5.*In response to the final argument:Yes it is very true that any number divided by itself yeilds one. Itis also true that zero divided by any number is zero. Likewise anynumber divided by zero is undefined (infinite). So we have 3competing definitions for 0/0:1. 0/0=1 since any number divided by itself =12. 0/0=0 since zero divided by any number =03. 0/0=inf since any number divided by zero is infinite or undefinedSo what is 0/0? It is not defined (because of the three competingdefinitions), by introducing limits the value of 0/0 can be any finitenumber, or infinity (but for this we need to be at the calculuslevel). ==== =>-----Original Message----->Sent: Sunday, October 27, 2002 12:33 PM>To: mathgroup@smc.vnet.net>This is not quite aposite to either NG, but there appear to be >none better>... My apologies.>>I am searching for an algorithm for producing a random >derangement of, for>instance, the integers 1 to approx 10000.>>I thought Skiena's site might have such an algorithm, but I >could not locate>one. ... Producing all derangements and choosing one at random >is marginally>beyond the capacity of my machine :-)>>Mark R. Diamond>>Mark,the idea just to generate random permutations and then just drop those whichare no derangements has already been proposed by Rob Pratt. (I leave outissues of compilation here.)permutation[n_]:=Module[{deck=Range[n],newj},Do[newj= Random[Integer,{j,n}]; deck[[{j,newj}]]=deck[[{newj,j}]],{j,n-1}]; deck]derangementQ[n_][perm_] := Not[Or @@ Equal @@@ Transpose[{Range[n ], perm}]]derangement3[n_] := Module[{p}, While[! derangementQ[n][p = permutation[n]]]; p]This will then give equal probabilitiy to every derangement. We mayaccelerate this, backing out, when a non-derangement _begins_ to evolve:derangement4[n_] := Module[{deck, newj}, While[deck = Range[n]; Catch[Do[newj = Random[Integer, {j, n}]; If[deck[[j]] == j == newj, Throw[True]]; deck[[{j, newj}]] = deck[[{newj, j}]], {j, n}]]]; deck]This also gives equal probabilities. Interestingly this will work too:derangement5[n_] := Module[{deck, newj}, While[deck = Range[n]; Catch[Do[If[deck[[j]] == j, If[Random[Integer, {j, n}] == n, Throw[True]]]; newj = Random[Integer, {j + If[deck[[j]] == j, 1, 0], n}]; deck[[{j, newj}]] = deck[[{newj, j}]], {j, n}]]]; deck]The line... If[Random[Integer, {j, n}] == n, Throw[True]]...adjusts the probabilities in case of deck[[j]]==j and also checks for acritical case when j == n.--Hartmut Wolf ==== =Dear MathGroup,I am in the process of learning to use Mathematica. Here are a couple of questions that I want to ask the group.1) Can I define a new object, Tensor, which will act like Complex? So, two Times[TensorA, TensorB] or TensorA*TensorB will invoke proper Times function to handle it.2) If the answer to the above question is yes, then can I use super/sub-scripts to represent the indices for the Tensor, and carry out the calculation based on these indices? Such as, g^uv*T_vk will get T^u_k, which essentially raises the first index of T_vk. Another example would be g^uv*T_uv will get a scalor T.I know there are couple of Tensor analysis packages, comercial and free, out there. But, all the free packages I looked through won't be able to do this. And, figuring out how to do stuff is the best to learn how to use Mathematica.Maybe, I am pursuing a dragon egg here. But, I'd still like to hear about how well Mathematica can do to imitate this behavior.Liguo ==== =In studying ßuid mechanics, I have been trying to understand Gausstheorem in general form for a tensor of order n. To make thingssimple, I consider two-dimensional space. Then my understanding isthat for a vector v = v1(x1,x2)i + v2(x1,x2)j:(A) Integral over volume of D[vi,xi] = integral over surface of vi*niwhere ni is normal in i direction. This equation is a singleequation, which can be written explicitly (i.e. performing summationover i) as(B) Integral over volume of D[v1,x1]+D[v2,x2] = integral over surfaceof v1*n1 + v2*n2.Now, this is Gauss theorem for a vector. However, Gauss theorem forscalar, F, states that(C) Integral over volume of D[F,xi] = integral over surface of F*nior explicitly, it yields two equations:(D1) Integral over volume of D[F,x1] = integral over surface of F*n1(D2) Integral over volume of D[F,x2] = integral over surface of F*n2I am unable to understand the relation between Gauss theorem forscalar and that for vector (not to mention 2nd order tensor), becausethe following seems a contradiction: Consider each component of thevector, v, discussed above to be a scalar function (i.e. v1(x1,x2) isa scalar). Then the scalar form of Gauss theorem implies that(E1) Integral over volume of D[v1,x1] = integral over surface ofv1*n1.(E2) Integral over volume of D[v2,x2] = integral over surface of v2*n2Actually, applying the scalar form of Gauss theorem completely to eachcomponent of v, will yield two more equations in addition to just E1and E2. Anyway, equations E1 and E2 imply that equation (B) above, isactually just the sum of equations E1 and E2.However, I have been told by my profressor that equations E1 and E2are not valid. Where is my reasoning wrong?Karl ==== =This is a minor, but annoying, problem. I would like to havethe 3 palettes that I use come up in the same screen location each time I start the Front End. I run Mathematica 4.1 under X, withI have read through the entire help section for Front End preferences,and couldn't find anything. Wondered if anyone knew how to do it, or knewthat it was indeed impossible.TimPS -> Some X window managers can do this automatically, withoutMathematica even knowing about it, but I am running KDE, andit does not seem to be able to do so for a non-KDE applicationsuch as Mathematica. A KDE hack would be welcome, too, if anyonehappened to know how. ==== =But you are yourself describing precisely this contrast! Moreover, the contrast between function oriented programming and object oriented programming was not invented on this list but is well known and quite often discussed. See for example the discussion in Part II of Mastering Mathematica by J.W. Grey, particularly the section entitled The Duality between Functions and Data, or various discussions in books on CLOS (object oriented common Lisp). What you are saying is in fact exactly the approach taken in CLOS. But it is also pretty sure that not everybody using Mathematica needs the kind of data and program structuring that object oriented programming provides, in fact I am pretty sure the majority of Mathematica users do not (the majority of users do not even need the existing package mechanism). It does not mean of course you should not develop your OOP package; in fact I am quite keen to try it when it becomes available.Andrzej Kozlowski> There is a tendency to see a contrast between OO and Mathematica. In my> opinion this makes no sense:> OO descibes a method for structuring programs and the data related to > the> programs. Mathemtica describes the instructions with which programs > may be> built.> Hermann Schmitt>>> ==== =>> This is not quite aposite to either NG, but there appear to be none better> ... My apologies.>> I am searching for an algorithm for producing a random derangement of, for> instance, the integers 1 to approx 10000.>> I thought Skiena's site might have such an algorithm, but I could not locate> one. ... Producing all derangements and choosing one at random is marginally> beyond the capacity of my machine :-)> Mark R. Diamond> One thing that will work efficiently is a modification of a basic random> shufße. The basic shufße can be found at> http://forums.wolfram.com/mathgroup/archive/2001/Apr/msg00263 .html> The modification is that at step j we insist on moving something between> position j+1 (rather than j) and the end into position j.> derangement = Compile[{{n,_Integer}}, Module[> {deck=Range[n], newj},> Do[> newj = Random[Integer, {j+1,n}];> deck[[{j,newj}]] = deck[[{newj,j}]],> {j,n-1}];> deck> ]]> In[4]:= Timing[dd = derangement[10^6];]> Out[4]= {5.25 Second, Null}> Check that this is indeed a derangement:> In[5]:= Select[Transpose[{dd,Range[10^6]}], #[[1]]==#[[2]]&]> Out[5]= {}> (Or you can use MapIndexed for this test):> In[12]:= Apply[Or, MapIndexed[#1==#2[[1]]&, dd]]> Out[12]= False> I think this will give random derangements with equal probabilities> though I don't have a proof of that off the top of my head.> Daniel Lichtblau> Wolfram ResearchOops...my code was itself a bit deranged insofar as it will not hit allpossible derangements. I think the version below will do better.derangement = Compile[{{n,_Integer}}, Module[ {deck=Range[n], newj}, Do[ newj = Random[Integer, {j+If[deck[[j]]==j,1,0],n}]; deck[[{j,newj}]] = deck[[{newj,j}]], {j,n-1}]; deck ]]Daniel LichtblauWolfram Research ==== => This is not quite aposite to either NG, but there appear to be none better> ... My apologies.> I am searching for an algorithm for producing a random derangement of, for> instance, the integers 1 to approx 10000.> I thought Skiena's site might have such an algorithm, but I could not locate> one. ... Producing all derangements and choosing one at random is marginally> beyond the capacity of my machine :-)> Mark R. DiamondOne thing that will work efficiently is a modification of a basic randomshufße. The basic shufße can be found athttp://forums.wolfram.com/mathgroup/archive/2001/Apr/ msg00263.htmlThe modification is that at step j we insist on moving something betweenposition j+1 (rather than j) and the end into position j.derangement = Compile[{{n,_Integer}}, Module[ {deck=Range[n], newj}, Do[ newj = Random[Integer, {j+1,n}]; deck[[{j,newj}]] = deck[[{newj,j}]], {j,n-1}]; deck ]]In[4]:= Timing[dd = derangement[10^6];]Out[4]= {5.25 Second, Null}Check that this is indeed a derangement:In[5]:= Select[Transpose[{dd,Range[10^6]}], #[[1]]==#[[2]]&]Out[5]= {}(Or you can use MapIndexed for this test):In[12]:= Apply[Or, MapIndexed[#1==#2[[1]]&, dd]]Out[12]= FalseI think this will give random derangements with equal probabilitiesthough I don't have a proof of that off the top of my head.Daniel LichtblauWolfram Research ==== => This is not quite aposite to either NG, but there appear to be none better> ... My apologies.>> I am searching for an algorithm for producing a random derangement of, for> instance, the integers 1 to approx 10000.>> I thought Skiena's site might have such an algorithm, but I could not locate> one. ... Producing all derangements and choosing one at random is marginally> beyond the capacity of my machine :-)>> Mark R. DiamondYou could just repeatedly call RandomPermutation until you get aderangement.Needs[DiscreteMath`Combinatorica`]; RandomDerangement[n_] := Module[{p = {1}}, While[ !DerangementQ[p], p = RandomPermutation[n]]; p]The expected number of calls to RandomPermutation is approximately E.Rob PrattDepartment of Operations Researchhttp://www.unc.edu/~rpratt/ ==== =Your visualization sounds fun. As far as programming paradigms for implementation, I have a hopefully helpful suggestion on structuring your implementation.Object-Oriented Programming (OOP) is certainly more than just data encapsulation, a feat which modular programming performs just fine. Probably not the definitive reference, but FOLDOC's definition of OOP mentions both encapsulation and inheritance. Furthermore, OOP does not imply a particular syntax. For example, myinstance.mymethod(args) and mymethod(myinstance,args) are both perfectly legitimate OOP syntaxes.One of the primary benefits of OOP is that you can subclass pre-existing classes, _without modifying or recompiling_ the existing class code, and objects designed for the superclass can use the subclass without knowing it. This greatly facilitates the REUSE of code and increases the ßexibility of libraries. What amuses me is that the wild popularity of OOP seems to be _partly_ due to the new OOP languages having better module systems (than C, for example) as well as a syntax which encourages the use of modularity, and _partly_ due to people finding the metaphors of OOP helpful in structuring their thinking.The pervasiveness of the OOP paradigm has made it seem somewhat like the one true way to structure a program, but I think a moments reßection leads most people to concede that, while wonderful, it is not a panacea (e.g. the Standard Template Library for C++ is less OOP and more functional programming). One of the difficulties of OOP's pervasiveness is that it is the only paradigm many people know, so when they approach a problem in a language that does not support OOP, they both do not understand the new paradigm well enough to structure their thinking appropriately for the language and they do not know the necessary idioms to effectively express chunks of computation.All that said, you can build basic data hierarchies in your Mathematica programs quite easily if you encode the collection of data associated with an object as a list of rules and specialize function definitions (methods) using pattern matching. Here is a simple example:obj={name->instance of superclass,data->1};printname[{___,name->name_,___}]:=Print[ name]printname[obj]getdata[{___,data->data_,___}]:= datagetdata[obj]subobj={name->instance of subclass,data->2, subdata->{20,30}};printname[subobj]getdata[{___,data->data_, subdata->subdata_,___}]:={data,subdata}getdata[subobj]getdata [obj]You can formalize this is various ways, by defining object constructors and so on. At the very least, you want to avoid typing these pattern matches all the time. Assigning the pattern to a variable essentially defines a class type:class={___,name->name_,data->data_,___};subclass=Join[ class,{subdata->subdata_,___}];mymethod[class,a_]:=a* datamymethod[subclass,a_]:=a*data*{1,1}.subdatamymethod[obj,2 ]mymethod[subobj,2]Of course, there are other ways to this, but this is just an example of simple and natural way to provide basic data inheritance with method specialization in your Mathematica programs.Alex ==== = In my opinion, can you try this, maybe can resolve your problem. sol = NDSolve[{y'[t] == 1 - y[t], y[0] == 0}, y, {t, 0, 20}] fy = y /. sol[[1]] ANSWER = Table[Max[y[t] /. sol], {t, 0, 0.99, 0.99}] ANSWER = Table[Max[y[t] /. sol], {t, 0, 0.9999, 0.9999}]>> I wish to find the value of the independent variable in an> interpolating function that makes the dependent variable assume some> value of interest. For example,>> sol = NDSolve[{y'[t] == 1-y[t], y[0]==0}, y, {t, 0, 20}]> fy = y/.sol[[1]]>> produces an interpolating function. I would like to extract the> value of t that yields a value of 0.99 or 0.9999 (say) for y. Is> there a straightforward way of doing this?>> Phil> --> Philip M. Howe> Program Manager, Stockpile Surety> Los Alamos National Laboratory>> (505) 665-5332> (505) 667-9498> Mail Stop P945 ==== =You can do it like this :In[1]:=NDSolve[{y'[t] == 1-y[t], y[0]==0}, y[t], {t, 0, 20}]In[2]:=y[t_]=y[t]/.%[[1]]In[3]:=Plot[y[t],{t,0,10}, PlotRange->{0,2}]In[4]:=FindRoot[y[t]==.999,{t,1}]Meilleures salutationsFlorian JaccardEICN-HES-----Message d'origine-----Envoy.8e : jeu., 31. octobre 2002 10:42è : mathgroup@smc.vnet.netObjet : The equivalent of FindRoot for an interpolatingfunctionI wish to find the value of the independent variable in aninterpolating function that makes the dependent variable assume somevalue of interest. For example,sol = NDSolve[{y'[t] == 1-y[t], y[0]==0}, y, {t, 0, 20}]fy = y/.sol[[1]]produces an interpolating function. I would like to extract thevalue of t that yields a value of 0.99 or 0.9999 (say) for y. Isthere a straightforward way of doing this?Phil--Philip M. HoweProgram Manager, Stockpile SuretyLos Alamos National Laboratory(505) 665-5332(505) 667-9498Mail Stop P945 ==== =has anyone coded a Markov Chain Monte Carlo routine in Mathematica..., I am wondering to what degree Compiling the program in Mathematicawith the compile function will compare to the speed you get from C?Amit ==== =Philip,It is difficult with FindRoot because of the nature of your function and theinadequacies of FindRoot.sol = NDSolve[{y'[t] == 1 - y[t], y[0] == 0}, y, {t, 0, 20}]fy = y /. sol[[1]]{{y -> InterpolatingFunction[{{0., 20.}}, <>]}}InterpolatingFunction[{{0., 20.}}, <>]Just to see what the function looks like...Plot[fy[x], {x, 0, 20}, PlotRange -> {0, 1}];The InterpolatingFunction is only defined between 0 and 20. That givesFindRoot lots of problems.FindRoot[fy[x] == 0.99, {x, 15, 0, 20}]FindRoot::regex: Reached the point !({(-133.32815729997475`)}) whichis outside the region !({({0.`, 20.`})}).{x -> -133.328}I do not understand why FindRoot doesn't go to a bisection method once itgoes outside the range. I suppose there is a reason.In any case, Ted Ersek has a much better root finding package calledRootSearch. I believe it is available on MathSource. (My one objection tothe copy of his package that I have is that it is not in a well definedfolder. It was in my ExtraPackagesEnhancements folder, but the name in theBeginPackage statement did not correspond. So it wouldn't load. I simpleadded the Enhancement context to the name and then it loaded. I am notcertain how the MathSource copy works.)Needs[Enhancements`RootSearch`]xsol = RootSearch[fy[x] == 0.99, {x, 0, 20}][[1, 1]]x -> 4.60521fy[x] /. xsol0.99A very neat package.David Parkdjmp@earthlink.nethttp://home.earthlink.net/~djmp/Phil-- Philip M. HoweProgram Manager, Stockpile SuretyLos Alamos National Laboratory(505) 665-5332(505) 667-9498Mail Stop P945 ==== =Liguo,I think it is a dragon's egg and certainly not the best way to learnMathematica. Basically you would have to Unprotect and add new definitionsto Times and that would be only the start of it because how are you going todistinguish between superscripts and powers? How are you going to handlemixed up and down indices? How are you going to get nice output formatting?There are many nice tensor packages out there. The moderator of this grouphas the original powerful tensor package. As a way of learning some tensorcalculus I have been working with Renan Cabrera on a package calledTensorial. It can be obtained at my web site below. It is oriented towardlearning the basic mechanics and reproducing textbook problems. You can haveany symbols for tensor labels or indices. The index domain can be any rangeof numbers or a set of symbols. For example, {0,1,2,3} or {t,x,y,z} forrelativity problems. You can have colored indices to distinguish differentcoordinate frames.Here is how one would do your two problems in Tensorial.Needs[TensorCalculus`Tensorial`]SetMetric[{x, g}, IdentityMatrix[3]]DefineTensorShortcuts[{T, g}, 2]guu[u, v]Tdd[v, k]% // MetricSimplify(formatted output)(formatted output, but Tud[u,k] in shortcut notation.)guu[u, v]Tdd[u, v]% // IndexEinstein(formatted output)(formatted output but Tdd[1,1] + Tdd[2,2] + Tdd[3,3] in shortcut notation.)The DefineTensorShortcuts statement defines T and g as labels of secondorder tensors. The various up and down index configurations can be specifiedby appending u's or d's to the tensor label. So, for example, gud[i,j]is the shortcut for g with the first index i up, and the second index jdown. Isn't that easier than maneuvering between superscripts andsubscripts? MetricSimplify automatically carries our the raising or loweringof indices with the metric tensor. IndexEinstein automatically carries outsummations on paired up and down indices.David Parkdjmp@earthlink.nethttp://home.earthlink.net/~djmp/to represent the indices for the Tensor, and carry out the calculation basedonthese indices? Such as, g^uv*T_vk will get T^u_k, which essentially raisesthefirst index of T_vk. Another example would be g^uv*T_uv will get a scalor T.I know there are couple of Tensor analysis packages, comercial and free, outthere. But, all the free packages I looked through won't be able to do this.And, figuring out how to do stuff is the best to learn how to useMathematica.Maybe, I am pursuing a dragon egg here. But, I'd still like to hear abouthowwell Mathematica can do to imitate this behavior.Liguo ==== =I wish to find the value of the independent variable in an interpolating function that makes the dependent variable assume some value of interest. For example,sol = NDSolve[{y'[t] == 1-y[t], y[0]==0}, y, {t, 0, 20}] fy = y/.sol[[1]]produces an interpolating function. I would like to extract the value of t that yields a value of 0.99 or 0.9999 (say) for y. Is there a straightforward way of doing this?Phil-- Philip M. HoweProgram Manager, Stockpile SuretyLos Alamos National Laboratory(505) 665-5332(505) 667-9498Mail Stop P945Reply-To: kuska@informatik.uni-leipzig.de ==== =sol = NDSolve[{y'[t] == 1 - y[t], y[0] == 0}, y[t], {t, 0, 20}]fy = y[t] /. sol[[1]];FindRoot[fy == 0.99, {t, 1}]work fine. And you should add an argument to a functionif you ask for an argument. Jens> I wish to find the value of the independent variable in an> interpolating function that makes the dependent variable assume some> value of interest. For example,> sol = NDSolve[{y'[t] == 1-y[t], y[0]==0}, y, {t, 0, 20}]> fy = y/.sol[[1]]> produces an interpolating function. I would like to extract the> value of t that yields a value of 0.99 or 0.9999 (say) for y. Is> there a straightforward way of doing this?> Phil> --> Philip M. Howe> Program Manager, Stockpile Surety> Los Alamos National Laboratory> (505) 665-5332> (505) 667-9498> Mail Stop P945 ==== =The separation between list elements is determined by a ConversionOptionImport[test.dat, List, ConversionOptions -> {ListSeparators -> {n, r}}]-Dale>>This may be a stupid question but is there an easy way to import>complex numbers from a file into mathematica. I have written some c++>code that outputs a set of complex numbers to a file and I have been>trying to get them into mathematica. What format should I use?>>To give myself a clue I exported a couple of complex numbers from>Mathematica to see what the file would look like:>>Export[test.dat, {3 + 2 I, 1 + 0.5 I}, List];>>which gives me the following test.dat:>3 + 2 I>1 + 0.5 I>>so far so good - looks like thats the format I need my c++ code to>output but when i try>>test = Import[test.dat, List];>i get the following output>test = {3, +, 2, I, 1, +, 0.5, I}>>Can anyone help me? I want to be able to Import the file directly - I>would rather not simply import a big list of numbers and write a>function that makes the relavent ones complex. Any help would be much>appreciated>>Mike ==== =>> A place I believe OOP would naturally benefit Mathematica is in the>> area of>> XML and particularly implementing the DOM IDL. There seem to be some>> problems with Mathematica's XML implementation. I suspect a good OOP>> approach might help in preventing some of these problems in the>> future. As>> middle>> name.>> Since I know absolutely nothing about this I will diplomatically agree.> But I am now sure if this XML business is really related to the> Mathematica programming language?In its purest form an XML DTD is essentially a set of S-expressions. Mathematica expressions are simply M-expressions which can easily be converted to equivalent S-expressions. Since the Mathematica kernel is obviously very adept at the manipulation of M-expressions there is little reason to suspect it would be difficult to work with XML. In fact if you add downvalues for the heads of the S-expressions given in a DTD you immediately have an XML document processor. The XML DOM then is a specification for an engine for navigating the S-expressions in a DTD using an imperative language, ie. the read-eval loop used in LISP and Mathematica is implicit in the DOM.Sounds like it's time to restate Greenspun's tenth rule of programming Any sufficiently complicated C or Fortran program contains an ad-hoc, informally-specified bug-ridden slow implementation of half of Common Lisp. I also suggest Paul Graham's take on the utility of object orientation in LISP like languages http://www.paulgraham.com/noop.html. If you follow the link at the bottom of that page and the next you Incidentally, my personal preference in programming languages is not LISP, I prefer strong typing and lazy evaluation a la Haskell (haskell.org for the curious) but am trapped using imperative OO languages to put food on my table.Ssezi ==== => Object-Oriented Programming (OOP) is certainly more than just data> encapsulation, a feat which modular programming performs just fine.> Probably not the definitive reference, but FOLDOC's definition of OOP> oriented+programming> mentions both encapsulation and inheritance.> Furthermore, OOP does not imply a particular syntax. For example,> myinstance.mymethod(args) and mymethod(myinstance,args) are both> perfectly legitimate OOP syntaxes.>The FOLDOC definition is good but I prefer to refer people to the Object Orientation FAQ at http://www.cyberdyne-object-sys.com/oofaq/. As has been pointed out encapsulation already exists in any modular language, Mathematica has it through contexts, if you use header files correctly C has encapsulation, so do Modula, Ada and nearly any other language developed since 1970.Inheritance is a sticky subject. It derives (no pun intended) from system design considerations but in practice it is closely tied to attempts to increase code reuse in strongly typed, static, imperative languages. Note that Mathematica has none of these qualities. See section 1.7 of the OO FAQ for a cogent discussion of inheritance. Since everything in Mathematica is of the same type: an expression and in the most general case a function can take any expression as an argument there is little need for inheritance in Mathematica. Instead Mathematica programmers can force inheritance structures by restricting function arguments to a particular pattern in which case the pattern could be considered to define a type and if the pattern is appropriately designed as Alexander did in his examples then we could consider a hierarchy of types to which the function applies thus getting an inheritance tree.The biggest gain in my opinion from OOP is neither encapsulation, which has existed nearly as long as high level languages have been known, nor inheritance which necessarily exists in languages with pattern matching facilities such as Prolog and thus also has been known to programmers since long before the current OOP craze. The main facility for code reuse is polymorphism which in my opinion is closely related to inheritance but obviously is not identical, see section 2 of the OO FAQ. Again, Mathematica has always supported polymorphism through the possibility of a function having multiple downvalues. However the downvalue and pattern matching mechanism together are more akin to parametric polymorphism. Here is where I show myself to be a heretic: parametric polymorphism and encapsulation are all you need for OOP, inheritance is unnecessary. If you define an appropriate set of polymorphic functions then your inheritance hierarchy will be implicitly defined. I admit that this is an extreme view.> One of the primary benefits of OOP is that you can subclass> pre-existing classes, _without modifying or recompiling_ the existing> class code, and objects designed for the superclass can use the> subclass without knowing it. This greatly facilitates the REUSE of code> and increases the ßexibility of libraries.And ultimately that is the goal: a small ßexible library. However I will repeat my heresy, you can either design an elaborate inheritance hierarchy and specialize methods from the base class as you descend or equivalently you can define a set of types (or patterns although the two are not exactly equivalent) and an appropriate set of functions on preferable, for implementation however the latter seems to me to be more effective.> The pervasiveness of the OOP paradigm has made it seem somewhat like> the one true way to structure a program, but I think a moments> reßection leads most people to concede that, while wonderful, it is> not a panacea (e.g. the Standard Template Library for C++ is less OOP> and more functional programming).Or functional programming (with patterns/guards or strong typing) is more OOP than we realized.> Of course, there are other ways to this, but this is just an example of> simple and natural way to provide basic data inheritance with method> specialization in your Mathematica programs.>Is it just me or does this resemble the Common Lisp Object System? Is that a coincidence? I have always believed that Mathematica possessed the necessary facilities for OOP the problem is the amount of programmer effort necessary to program in an OOP style with Mathematica. So it seems some kind of syntactic assistance is all that is necessary: functions to allow easy definition of constructors, destructors, class relationships etc. and easy inspection of the same. My guess is that the end result will closely resemble CLOS but given the protest most programmers make when faced with the LISP paradigm I think many Mathematica users would be unhappy with the end result.Sseziwa ==== =>> Any suggestions for the evaluation of the following ?> FourierTransform[> KroneckerDelta[f-(-1 + 10^(n T/c)/b)], f, t]>> or even this :> FourierTransform[> DiracDelta[f-(-1 + 10^(n T/c)/b)], f, t]>> Mathematica simply spits back the same input.>>TryFourierTransform[ DiracDelta[f-(-1 + 10^(n T/c)/b)], f, t,Assumptions->{Element[f,Reals]}] ==== =Not as such. If you look at ListPlot3D in the Help Browser, you'll noticethat the argument to this function is an array. In ListPlot you may havedifferent size intervals between the x points, while in ListPlot3D you musthave a regular set of points which are the f[x,y] in {x, y, f[x, y]}. Thereare some ways to handle this: one is to complete the missing points in yourlist in order to have an array; another is to use alternative functions suchas Graphics`Graphics3D`ScatterPlot3D.Tomas GarzaMexico City----- Original Message ----->> ==== =ist there a possibility analog to the 2dListPlot[{x1,f[x1]},{x2,f[x2]},...] also in 3d, i.e.ListPlot3D[{x1,y1,f[x1,y1]}, {x2,y2,f[x2,y2]}, ....]thank you for any help in advance.Erwin.Reply-To: kuska@informatik.uni-leipzig.de ==== =< ist there a possibility analog to the 2d> ListPlot[{x1,f[x1]},{x2,f[x2]},...] also in 3d, i.e.> ListPlot3D[{x1,y1,f[x1,y1]}, {x2,y2,f[x2,y2]}, ....]> thank you for any help in advance.> Erwin. ==== =Using Export[Test.dat, {3 + 2 I, 1 + 0.5 I}, Expression] will get you the file with the following content:{3 + 2*I, 1 + 0.5*I}Then, use Import[Test.dat,Expression] will get {3+2 I, 1+0.5 I}. So, try to make your program out in this format and then import as Expression.Hope it helps.Liguo> This may be a stupid question but is there an easy way to import> complex numbers from a file into mathematica. I have written some c++> code that outputs a set of complex numbers to a file and I have been> trying to get them into mathematica. What format should I use?> To give myself a clue I exported a couple of complex numbers from> Mathematica to see what the file would look like:> Export[test.dat, {3 + 2 I, 1 + 0.5 I}, List];> which gives me the following test.dat:> 3 + 2 I> 1 + 0.5 I> so far so good - looks like thats the format I need my c++ code to> output but when i try> test = Import[test.dat, List];> i get the following output> test = {3, +, 2, I, 1, +, 0.5, I}> Can anyone help me? I want to be able to Import the file directly - I> would rather not simply import a big list of numbers and write a> function that makes the relavent ones complex. Any help would be much> appreciated> Mike ==== =One possibility is that you keep your source data as a CSV file. Forexample,In[1]:=Export[test.dat, {3 + 2*I, 1 + 0.5*I}, CSV];In[2]:=test = Import[test.dat, CSV]Out[2]={{3 + 2*I, 1 + 0.5*I}}As you can see, the imported data are strings. Then use ToExpression toconvert them to numbers:In[3]:=a = ToExpression[test]Out[3]={{3 + 2*I, 1 + 0.5*I}}In[4]:=Head[a[[1,1]]]Out[4]=ComplexI guess this is what you were looking for.Tomas GarzaMexico City----- Original Message -----> Mathematica to see what the file would look like:>> Export[test.dat, {3 + 2 I, 1 + 0.5 I}, List];>> which gives me the following test.dat:> 3 + 2 I> 1 + 0.5 I>> so far so good - looks like thats the format I need my c++ code to> output but when i try>> test = Import[test.dat, List];> i get the following output> test = {3, +, 2, I, 1, +, 0.5, I}>> Can anyone help me? I want to be able to Import the file directly - I> would rather not simply import a big list of numbers and write a> function that makes the relavent ones complex. Any help would be much> appreciated>> Mike>> ==== =>> This may be a stupid question but is there an easy way to import> complex numbers from a file into mathematica. I have written some c++> code that outputs a set of complex numbers to a file and I have been> trying to get them into mathematica. What format should I use?>> To give myself a clue I exported a couple of complex numbers from> Mathematica to see what the file would look like:>> Export[test.dat, {3 + 2 I, 1 + 0.5 I}, List];>> which gives me the following test.dat:> 3 + 2 I> 1 + 0.5 I>> so far so good - looks like thats the format I need my c++ code to> output but when i try>> test = Import[test.dat, List];> i get the following output> test = {3, +, 2, I, 1, +, 0.5, I}>> Can anyone help me? I want to be able to Import the file directly - I> would rather not simply import a big list of numbers and write a> function that makes the relavent ones complex. Any help would be much> appreciated>If you are only going to read the file in Mathematica output the results as a Mathematica expression e.g. {3+2 I, 1+0.5 I} and use << to read it in Mathematica.SseziReply-To: munsup.seoh@wright.edu ==== =I have a question. Please help me. Can I solve the following equation witha simple Solve command in Mathematica?((x1, x2, x3, x4): x1 + x2 + x3 + x4 == 4; x1, x2, x3, x4 are nonnegativeintegers}Munsup Seoh, PhD, ProfessorDepartment of Mathematics and StatisticsWright State University3640 Colonel Glenn HwyDayton, OH 45435Homepage: www.wright.edu/~munsup.seoh ==== =>Consider yer basic 3d6 stat roll: What are the possibilities?>This gives a table of all 6^3 = 216 rolls:>>Table[i + i2 + i3, {i, 6}, {i2, 6}, {i3, 6}] // MatrixForm>>My question is this: How shall I set up a formula to list the count of>each>total?>lst = Table[i + i2 + i3, {i, 6}, {i2, 6}, {i3, 6}] // Flatten;ans1 = ({#1, Count[lst, #1]} &) /@ Range[3, 18]{{3, 1}, {4, 3}, {5, 6}, {6, 10}, {7, 15}, {8, 21}, {9, 25}, {10, 27}, {11, 27}, {12, 25}, {13, 21}, {14, 15}, {15, 10}, {16, 6}, {17, 3}, {18, 1}}ans1 == ({First[#], Length[#]} & /@ (lst // Sort // Split))TrueNeeds[Statistics`DataManipulation`];ans1 == Reverse /@ Frequencies[lst]TrueBob Hanlon ==== =>I wish to find the value of the independent variable in an >interpolating function that makes the dependent variable assume some >value of interest. For example,>>sol = NDSolve[{y'[t] == 1-y[t], y[0]==0}, y, {t, 0, 20}] >fy = y/.sol[[1]]>>produces an interpolating function. I would like to extract the >value of t that yields a value of 0.99 or 0.9999 (say) for y. Is >there a straightforward way of doing this?>The exact solution isy[t] /. DSolve[{y'[t] == 1 - y[t], y[0] == 0}, y[t], t][[1]] // Simplify1 - E^(-t)sol = y /. NDSolve[{y'[t] == 1 - y[t], y[0] == 0}, y, {t, 0, 20}] [[1]];f[x_] := t /. FindRoot[sol[t] == x, {t, -Log[1 - x]}];f /@ {.9, .99, .999, .9999, .99999}{2.302585092994046, 4.605170185988091, 6.907755278982136, 9.210340371976294, 11.51292546497478}Plot[sol[t], {t, 0, 10}];Plot[f[x], {x, .5, .99999}];Bob Hanlon ==== =Suppose I'm building a complex array of plots with the structure: Show[ GraphicsArray[{ DisplayTogether[--multiple plots--, <--DT options-->], DisplayTogether[--multiple plots--, <--DT options-->], DisplayTogether[--multiple plots--, <--DT options-->] }, <--GA options--> ], <--Show options-->];where the --multiple plots-- include Plot's, ListPlot's and ParametricPlot's, and I want *every* individual plot in the final result to have AspectRatio->Automatic.Should I be able to accomplish this in a global fashion by setting that option in the Show options only? Or in the GA options? Or in each of the DT options? Or do I have to do it in every single individual plot?(I've done some tests and seem to get inconsistent answers. In fact, I've put that option into every single possible place, and sometimes still seem to get individual plots that don't obey it.) ==== =One can define the function d0 for dice, thatcreates the table of xd0y rolls, in a different formthan yours:In: d0[x_Integer, y_Integer] := Module[{A}, A = Table[i, {i, y}]; Nest[Flatten[Outer[Plus, #1, A]] &, A, x - 1] ]This can be called infix, therefore one would getIn: 3~d0~4Out: {3, 4, 5, 6, 4, 5, 6, 7, 5, 6, 7, 8, 6, 7, 8, 9, 4, 5,6, 7, 5, 6, 7, 8, 6, 7, 8, 9, 7, 8, 9, 10, 5, 6, 7, 8,6, 7, 8, 9, 7, 8, 9, 10, 8, 9, 10, 11, 6, 7, 8, 9, 7,8, 9, 10, 8, 9, 10, 11, 9, 10, 11, 12}Afterwards we can define the function d that countsthe results in the following way:In:d[x_Integer, y_Integer] := Module[{A, AMx, AMn}, A = x~d0~y; AMx = Max[A]; AMn = Min[A]; Table[{i, Count[A, z_ /; z == i]}, {i, AMn, AMx}] ]For example,In: 3~d~4Out: {{3, 1}, {4, 3}, {5, 6}, {6, 10}, {7, 15}, {8, 21},{9, 25}, {10, 27}, {11, 27}, {12, 25}, {13, 21}, {14,15}, {15, 10}, {16, 6}, {17, 3}, {18, 1}}The results is {roll,number of occurences}I suppose you would be interested in getting a barchart with the result. We can use the BarChartfunction of the Graphics package to define the newfunction dB for bar chart:In:<< Graphics`Graphics`dB[x_Integer, y_Integer] := Module[{B}, B = x~d~y // Transpose; BarChart[B[[2]], Ticks -> {Transpose[{Table[i, {i,Length[B[[1]]]}], B[[1]]}], Automatic}]; ]Then, if you inputIn: 3~dB~4you would get a bar chart with the results of a 3d4roll.Hope it helps,Kyriakos_____+**+____+**+___+**+__+**+_Kyriakos ChourdakisLecturer in Financial EconomicsURL: http://www.qmw.ac.uk/~te9001tel: (++44) (+20) 7882 5086Dept of EconomicsUniversity of London, QMLondon E1 4NSU.K. ==== ================================================= Consider yer basic 3d6 stat roll: What are thepossibilities?This gives a table of all 6^3 = 216 rolls:Table[i + i2 + i3, {i, 6}, {i2, 6}, {i3, 6}] //MatrixFormMy question is this: How shall I set up a formula tolist the count of eachtotal? ==== ================================================ =__________________________________________________Do You Yahoo!?Everything you'll ever need on one web pagehttp://uk.my.yahoo.com ==== =>ist there a possibility analog to the 2d>ListPlot[{x1,f[x1]},{x2,f[x2]},...] also in 3d, i.e.>ListPlot3D[{x1,y1,f[x1,y1]}, {x2,y2,f[x2,y2]}, ....]>See the function ScatterPlot3D in the add-on package Graphics`Graphics3D`Bob HanlonReply-To: ==== =Table[i + i2 + i3, {i, 6}, {i2, 6}, {i3, 6}]{First@#, Length@#} & /@ Split@Sort@Flatten@%DrBob-----Original Message----- ==== =Mathematica is primarily a system for doing interactive computations, OO isnot suitable for those cases, at least directly, but classes could be asubstitute for packages. If you store above menhtioned computions in orderto avoid reenter, this is not a case for OO, either.But Mathematica is - in my eyes - one of the best programming languages andalso applicable beyond Mathematical computations. There are no facilitiesfor building GUI's and working with databases, but J/Link makes it possibleto use these facilities in Java. It makes not much sense that invent thewheel again, for theses facilities.As I consider Mathematica a very good programming language, it makes senseto program larger applications in Marthematica, and then OO comes into theplay.Hermann Schmitt----- Original Message -----> that not everybody using Mathematica needs the kind of data and> program structuring that object oriented programming provides, in fact> I am pretty sure the majority of Mathematica users do not (the> majority of users do not even need the existing package mechanism).> It does not mean of course you should not develop your OOP package; in> fact I am quite keen to try it when it becomes available.>> Andrzej Kozlowski>>> There is a tendency to see a contrast between OO and Mathematica. In my> opinion this makes no sense:> OO descibes a method for structuring programs and the data related to> the> programs. Mathemtica describes the instructions with which programs> may be> built.> Hermann Schmitt>>> ==== => My point is, that Mathematica is not based on functional programming.> Mathematica is essentially a set of instructions, which can be > structured> into programs in several ways.This seems to me a vacuous statement, or rather one that can be made about any complete programming language. Certainly you can write in Mathematica an interpretor for any other programming language, so in that sense you can also structure your programs in any way you like. But Mathematica has its own natural language any there is hardly anyone who doubts that it is based on a mixture of Lisp-like functional programming and Prolog-like logic programming. As for OOP, as you say: pre-requsites are missing. They are missing presumably because people at WRI do not think they would make a tremendous addition to Mathematica's capabilities. I also share this view, which does not mean that less than world shattering addition would not be interesting and useful.Andrzej KozlowskiYokohama, Japanhttp://www.mimuw.edu.pl/~akoz/http:// platon.c.u-tokyo.ac.jp/andrzej/ ==== => My point is, that Mathematica is not based on functional programming.> Mathematica is essentially a set of instructions, which can be > structured> into programs in several ways.> They are missing presumably because > people at WRI do not think they would make a tremendous addition to > Mathematica's capabilities. I also share this view, which does not mean > that less than world shattering addition would not be interesting and > useful.As one voice in the wilderness, I would be THRILLED for some OOPconstructs in Mathematica, primarily to make my code more readable. Wedo a lot of rule capture for engineering systems, and support forSTRUCTs or STRUCT-like entities would help. ==== =Is the following a bug or a feature?I had expected thatIn[1]:= rep={f[x1_,x2_]->x2};defines a replacement rule, where f is replaced by its second argument.However,In[2]:= Table[ {x1 ,f[x2,x1] /.rep} , {x2, 1,2},{x1, 1,2}]givesOut[2]= {{{1, 1}, {2, 1}}, {{1, 2}, {2, 2}}}instead of {{{1,1},{2,2}},{{1,1},{2,2}}} obviously because the value forx2 in the rule rep is not determined from the pattern at the LHS butfrom the summation argument.I assumed, that definitions involving patterns are always local... AchimP.S. One solution for the problem is to use :> innstead of ->Reply-To: kuska@informatik.uni-leipzig.de ==== =what may RuleDelayed[] do ??rep = {f[x1_, x2_] :> x2};Table[{x1, f[x2, x1] /. rep}, {x2, 1, 2}, {x1, 1, 2}] Jens> Is the following a bug or a feature?> I had expected that> In[1]:= rep={f[x1_,x2_]->x2};> defines a replacement rule, where f is replaced by its second argument.> However,> In[2]:= Table[ {x1 ,f[x2,x1] /.rep} , {x2, 1,2},{x1, 1,2}]> gives> Out[2]= {{{1, 1}, {2, 1}}, {{1, 2}, {2, 2}}}> instead of {{{1,1},{2,2}},{{1,1},{2,2}}} obviously because the value for> x2 in the rule rep is not determined from the pattern at the LHS but> from the summation argument.> I assumed, that definitions involving patterns are always local...> Achim> P.S. One solution for the problem is to use :> innstead of -> ==== =you may use entries with Head Tensor, e.g. Tensor[xyz], where xyzidentifies an specific Tensor.Then you can define functions Plus, Times, ... in the form:Plus[x__Tensor] := .......x__ Tensor means one ore more expressions with Head Tensor.Hermann Schmitt----- Original Message ----->> Second, output formatting can be done easily withSubsuperscriptBox[string, sub,> sup], where string represents the name of the Tensor, sub/sup are stringsto> represent the scripts for the tensor. Spaces can be used to align the suband> super-scripts.>> So, it boils down the my first question, how can I define a object,Tensor,> which will behave like Complex? So, I can redefine Times, Plus, Minus, andother> operators to handle Tensor.>> Also, how can I relate a symble to a Function as + relates Plus, * relatesto Times?>> Again, thanks for your thoughts on this topic.> Liguo> Liguo,>> I think it is a dragon's egg and certainly not the best way to learn> Mathematica. Basically you would have to Unprotect and add newdefinitions> to Times and that would be only the start of it because how are yougoing to> distinguish between superscripts and powers? How are you going to handle> mixed up and down indices? How are you going to get nice outputformatting?>> There are many nice tensor packages out there. The moderator of thisgroup> has the original powerful tensor package. As a way of learning sometensor> calculus I have been working with Renan Cabrera on a package called> Tensorial. It can be obtained at my web site below. It is orientedtoward> learning the basic mechanics and reproducing textbook problems. You canhave> any symbols for tensor labels or indices. The index domain can be anyrange> of numbers or a set of symbols. For example, {0,1,2,3} or {t,x,y,z} for> relativity problems. You can have colored indices to distinguishdifferent> coordinate frames.>> Here is how one would do your two problems in Tensorial.>> Needs[TensorCalculus`Tensorial`]> SetMetric[{x, g}, IdentityMatrix[3]]>> DefineTensorShortcuts[{T, g}, 2]>> guu[u, v]Tdd[v, k]> % // MetricSimplify> (formatted output)> (formatted output, but Tud[u,k] in shortcut notation.)>> guu[u, v]Tdd[u, v]> % // IndexEinstein> (formatted output)> (formatted output but Tdd[1,1] + Tdd[2,2] + Tdd[3,3] in shortcutnotation.)>> The DefineTensorShortcuts statement defines T and g as labels of second> order tensors. The various up and down index configurations can bespecified> by appending u's or d's to the tensor label. So, for example,gud[i,j]> is the shortcut for g with the first index i up, and the second index j> down. Isn't that easier than maneuvering between superscripts and> subscripts? MetricSimplify automatically carries our the raising orlowering> of indices with the metric tensor. IndexEinstein automatically carriesout> summations on paired up and down indices.>> David Park> djmp@earthlink.net> http://home.earthlink.net/~djmp/> To: mathgroup@smc.vnet.net>> Dear MathGroup,>> I am in the process of learning to use Mathematica. Here are a couple of> questions that I want to ask the group.>> 1) Can I define a new object, Tensor, which will act like Complex? So,two> Times[TensorA, TensorB] or TensorA*TensorB will invoke proper Timesfunction> to> handle it.>> 2) If the answer to the above question is yes, then can I use> super/sub-scripts> to represent the indices for the Tensor, and carry out the calculationbased> on> these indices? Such as, g^uv*T_vk will get T^u_k, which essentiallyraises> the> first index of T_vk. Another example would be g^uv*T_uv will get ascalor T.>> I know there are couple of Tensor analysis packages, comercial and free,out> there. But, all the free packages I looked through won't be able to dothis.> And, figuring out how to do stuff is the best to learn how to use> Mathematica.>> Maybe, I am pursuing a dragon egg here. But, I'd still like to hearabout> how> well Mathematica can do to imitate this behavior.>> Liguo>> ==== =here are my answers for the questions that you brought out.First, about the super/sub-scripts. I can easily use a list of True/False for sub/super-script. I can combine this list with the List that represent the tensor together to for a new object, Tensor.Second, output formatting can be done easily with SubsuperscriptBox[string, sub, sup], where string represents the name of the Tensor, sub/sup are strings to represent the scripts for the tensor. Spaces can be used to align the sub and super-scripts.So, it boils down the my first question, how can I define a object, Tensor, which will behave like Complex? So, I can redefine Times, Plus, Minus, and other operators to handle Tensor.Also, how can I relate a symble to a Function as + relates Plus, * relates to Times?Again, thanks for your thoughts on this topic.Liguo> Liguo,> I think it is a dragon's egg and certainly not the best way to learn> Mathematica. Basically you would have to Unprotect and add new definitions> to Times and that would be only the start of it because how are you going to> distinguish between superscripts and powers? How are you going to handle> mixed up and down indices? How are you going to get nice output formatting?> There are many nice tensor packages out there. The moderator of this group> has the original powerful tensor package. As a way of learning some tensor> calculus I have been working with Renan Cabrera on a package called> Tensorial. It can be obtained at my web site below. It is oriented toward> learning the basic mechanics and reproducing textbook problems. You can have> any symbols for tensor labels or indices. The index domain can be any range> of numbers or a set of symbols. For example, {0,1,2,3} or {t,x,y,z} for> relativity problems. You can have colored indices to distinguish different> coordinate frames.> Here is how one would do your two problems in Tensorial.> Needs[TensorCalculus`Tensorial`]> SetMetric[{x, g}, IdentityMatrix[3]]> DefineTensorShortcuts[{T, g}, 2]> guu[u, v]Tdd[v, k]> % // MetricSimplify> (formatted output)> (formatted output, but Tud[u,k] in shortcut notation.)> guu[u, v]Tdd[u, v]> % // IndexEinstein> (formatted output)> (formatted output but Tdd[1,1] + Tdd[2,2] + Tdd[3,3] in shortcut notation.)> The DefineTensorShortcuts statement defines T and g as labels of second> order tensors. The various up and down index configurations can be specified> by appending u's or d's to the tensor label. So, for example, gud[i,j]> is the shortcut for g with the first index i up, and the second index j> down. Isn't that easier than maneuvering between superscripts and> subscripts? MetricSimplify automatically carries our the raising or lowering> of indices with the metric tensor. IndexEinstein automatically carries out> summations on paired up and down indices.> David Park> djmp@earthlink.net> http://home.earthlink.net/~djmp/> Dear MathGroup,> I am in the process of learning to use Mathematica. Here are a couple of> questions that I want to ask the group.> 1) Can I define a new object, Tensor, which will act like Complex? So, two> Times[TensorA, TensorB] or TensorA*TensorB will invoke proper Times function> to> handle it.> 2) If the answer to the above question is yes, then can I use> super/sub-scripts> to represent the indices for the Tensor, and carry out the calculation based> on> these indices? Such as, g^uv*T_vk will get T^u_k, which essentially raises> the> first index of T_vk. Another example would be g^uv*T_uv will get a scalor T.> I know there are couple of Tensor analysis packages, comercial and free, out> there. But, all the free packages I looked through won't be able to do this.> And, figuring out how to do stuff is the best to learn how to use> Mathematica.> Maybe, I am pursuing a dragon egg here. But, I'd still like to hear about> how> well Mathematica can do to imitate this behavior.> Liguo> ==== => Dear MathGroup,>> I am in the process of learning to use Mathematica. Here are a couple > of> questions that I want to ask the group.>> 1) Can I define a new object, Tensor, which will act like Complex? So, > two> Times[TensorA, TensorB] or TensorA*TensorB will invoke proper Times > function to> handle it.>See the examples in the help for Outer.> 2) If the answer to the above question is yes, then can I use > super/sub-scripts> to represent the indices for the Tensor, and carry out the calculation > based on> these indices? Such as, g^uv*T_vk will get T^u_k, which essentially > raises the> first index of T_vk. Another example would be g^uv*T_uv will get a > scalor T.>Unfortunately tensors in Mathematica are represented as nested lists so no information about super or subscripts is retained. You have to keep track of that information yourself, but since Outer is defined the results of computations will be correct.> I know there are couple of Tensor analysis packages, comercial and > free, out> there. But, all the free packages I looked through won't be able to do > this.> And, figuring out how to do stuff is the best to learn how to use > Mathematica.>> Maybe, I am pursuing a dragon egg here. But, I'd still like to hear > about how> well Mathematica can do to imitate this behavior.>the tools are available in Mathematica to construct a Tensor Analysis package though. A quick search reveals the commercial package MathTensor from http://smc.vnet.net/MathTensor.html and the free package Ricci available at Sseziwa ==== =Exp[x] works; it is a syntax problem not a machine -size problem.-----Ursprí.b9ngliche Nachricht-----Gesendet: Freitag, 1. November 2002 07:43An: mathgroup@smc.vnet.netBetreff: machine-size problem again?Dear experts,I have a trouble in plotting e^x. Plot[e^x, {x, 1, 4}]It keeps telling me:e^x is not a machine-size real number at x = 1.000000125e^x is not a machine-size real number at x = 1.1217009747187472e^x is not a machine-size real number at x = 1.2544263995781209;Even I have added the modifier Evaluate.Plot[Evaluate[e^x], {x, 1, 4}]The output is the same. ==== =a further hint:by: lst = List[x__], where x__ specifies the paramters e.g. of thefunction Plus,you get a list of the paramters and you can access them, easily.Hermann Schmitt----- Original Message -----> ----- Original Message -----> To: > Sent: Friday, November 01, 2002 7:43 AM> while. And> here are my answers for the questions that you brought out.>> First, about the super/sub-scripts. I can easily use a list ofTrue/False> for> sub/super-script. I can combine this list with the List that representthe> tensor together to for a new object, Tensor.>> Second, output formatting can be done easily with> SubsuperscriptBox[string, sub,> sup], where string represents the name of the Tensor, sub/sup arestrings> to> represent the scripts for the tensor. Spaces can be used to align thesub> and> super-scripts.>> So, it boils down the my first question, how can I define a object,> Tensor,> which will behave like Complex? So, I can redefine Times, Plus, Minus,and> other> operators to handle Tensor.>> Also, how can I relate a symble to a Function as + relates Plus, *relates> to Times?>> Again, thanks for your thoughts on this topic.> Liguo> Liguo,>> I think it is a dragon's egg and certainly not the best way to learn> Mathematica. Basically you would have to Unprotect and add new> definitions> to Times and that would be only the start of it because how are you> going to> distinguish between superscripts and powers? How are you going tohandle> mixed up and down indices? How are you going to get nice output> formatting?>> There are many nice tensor packages out there. The moderator of this> group> has the original powerful tensor package. As a way of learning some> tensor> calculus I have been working with Renan Cabrera on a package called> Tensorial. It can be obtained at my web site below. It is oriented> toward> learning the basic mechanics and reproducing textbook problems. Youcan> have> any symbols for tensor labels or indices. The index domain can be any> range> of numbers or a set of symbols. For example, {0,1,2,3} or {t,x,y,z}for> relativity problems. You can have colored indices to distinguish> different> coordinate frames.>> Here is how one would do your two problems in Tensorial.>> Needs[TensorCalculus`Tensorial`]> SetMetric[{x, g}, IdentityMatrix[3]]>> DefineTensorShortcuts[{T, g}, 2]>> guu[u, v]Tdd[v, k]> % // MetricSimplify> (formatted output)> (formatted output, but Tud[u,k] in shortcut notation.)>> guu[u, v]Tdd[u, v]> % // IndexEinstein> (formatted output)> (formatted output but Tdd[1,1] + Tdd[2,2] + Tdd[3,3] in shortcut> notation.)>> The DefineTensorShortcuts statement defines T and g as labels ofsecond> order tensors. The various up and down index configurations can be> specified> by appending u's or d's to the tensor label. So, for example,> gud[i,j]> is the shortcut for g with the first index i up, and the second indexj> down. Isn't that easier than maneuvering between superscripts and> subscripts? MetricSimplify automatically carries our the raising or> lowering> of indices with the metric tensor. IndexEinstein automatically carries> out> summations on paired up and down indices.>> David Park> djmp@earthlink.net> http://home.earthlink.net/~djmp/> To: mathgroup@smc.vnet.net>> Dear MathGroup,>> I am in the process of learning to use Mathematica. Here are a coupleof> questions that I want to ask the group.>> 1) Can I define a new object, Tensor, which will act like Complex? So,> two> Times[TensorA, TensorB] or TensorA*TensorB will invoke proper Times> function> to> handle it.>> 2) If the answer to the above question is yes, then can I use> super/sub-scripts> to represent the indices for the Tensor, and carry out the calculation> based> on> these indices? Such as, g^uv*T_vk will get T^u_k, which essentially> raises> the> first index of T_vk. Another example would be g^uv*T_uv will get a> scalor T.>> I know there are couple of Tensor analysis packages, comercial andfree,> out> there. But, all the free packages I looked through won't be able to do> this.> And, figuring out how to do stuff is the best to learn how to use> Mathematica.>> Maybe, I am pursuing a dragon egg here. But, I'd still like to hear> about> how> well Mathematica can do to imitate this behavior.>> Liguo>>>