A50 == MathGroup and Newsgroup users:If you have posted messages in the last few days that have not appearedspool to lose these posts. The problem has been fixed and a new backupsystem installed.Sorry for the delay.Steve Christensen ==== There have been a several postings to Mathgroup recently concerningcalculus problems in Mathematica V4.2 which have been based ondevelopment versions of Mathematica. Wolfram Research createsdevelopment versions of our software in order to test different areasof functionality and new implementations. Sending reports to Mathgroupbased on these test versions is very confusing since readers maybelieve they refer to the official released versions. In addition, itseems more useful for reports to be based on versions of Mathematicathat are accessible to readers of Mathgroup.Specifically, the posting of July 5 entitled, ÔYet Another IntegrateHowler' refers to a development version. The released version ofMathematica V4.2 returns a correct result for this problem. In additionthe posting of July 1 entitled, ÔYet another bug in LaplaceTransform',refers to a problem that we cannot reproduce. We believe that this alsocomes from a test version.We have an active mechanism for tracking and collecting problems intest versions, and we strongly urge participants in our test programsto make use of these procedures.As ever, we are very interested in reports of problems in shippingversions of Mathematica. We cannot guarantee to resolve all of themimmediately, but we can guarantee to take them very seriously.Sincerely, Eric BynumTechnical Support ManagerWolfram Research, Inc.support@wolfram.com ==== [second posting in view of reported technical problem]Anthony,Take w = Table[Random[Integer], {200000}My first thought was, and several posts used this, Count[Partition[w, 2,1],{1,0}]//Timing {3.24 Second,49851}Later it occured to me to use arithmetic, which turned out to be twice asfast: Count[ Drop[w,-1] - Drop[w,1],1]//Timing {1.49 Second,49851}This is close to Selwyn Hollis's code Count[Drop[w+2RotateRight[w],1],2]//Timing {1.6 Second,49851}--Allan---------------------Allan HayesMathematica Training and ConsultingLeicester UKwww.haystack.demon.co.ukhay@haystack.demon.co.ukVoice : +44 (0)116 271 4198>> Suppose w={1,1,1,0,0,1,0,1,0,0,1,0,0}.>> How can I count the number of occurrences of a 1 in w immediately> followed by a 0 in w?>> I have tried every incarnation of Count[] I can think of; for example,>> Count[w,{___,1,0,___}]>> does not seem to work. In general, how can I count the number of> --> Tony> _____________________> amendes@math.ucsd.edu>> ==== howdy,i have a Problem of the FormM . v == 0where M is a complex, numerical, 8x8 Matrix and v is an Vector witheight unkown elements.M depends on one parameter x (real).There is no exact solution vor this equation. I will plotAbs[Det[M[x_]]]and watch for a local minimum. This way i can say: x must be something like... or ... or. Now I need to get the vector v in this point x. Any hints for a nice function to complete this task? Greetings ChristophReply-To: kuska@informatik.uni-leipzig.de ==== NullSpace[m] gives a list of vectors that forms a basis for the nullspace of the matrix m.?NullSpace[M /. x-> something like ... or ... ]??? Jens> howdy,> i have a Problem of the Form> M . v == 0> where M is a complex, numerical, 8x8 Matrix and v is an Vector with> eight unkown elements.> M depends on one parameter x (real).> There is no exact solution vor this equation. I will plot> Abs[Det[M[x_]]]> and watch for a local minimum. This way i can say: x must be something like> ... or ... or. Now I need to get the vector v in this point x.> Any hints for a nice function to complete this task?> Greetings> Christoph ==== I am also interesting in the solution of how to make an asumptionin Mathematica. I can't find any method in Mathematica. If anybody has> I know that this should be 0 but why can't I get mathematica to think> likewise.> In[4]:= Limit[Sin[a*x]/(a*x),x->Infinity]> Sin[a x]> Out[4]= Limit[--------, x -> Infinity]> a x> Is the problem a? How can I specify the properties of or assumptions> that may be made about a? ==== Anthony and newsgroup,I thought of another method of solving this problem which is 5 or 6 timesfaster than my previous version. Here is a test case.tst=Table[Random[Integer],{1000000}];My first solution wasIn[16]:=Count[Partition[tst,2,1],{1,0}]//TimingOut[16 ]={0.704 Second, 249722}My second solution isIn[17]:=Tr[Drop[tst,-1](Drop[tst,-1]-Drop[tst,1])]// TimingOut[17]={0.125 Second, 249722}Carl WollPhysics DeptU of Washington>> Suppose w={1,1,1,0,0,1,0,1,0,0,1,0,0}.>> How can I count the number of occurrences of a 1 in w immediately> followed by a 0 in w?>> I have tried every incarnation of Count[] I can think of; for example,>> Count[w,{___,1,0,___}]>> does not seem to work. In general, how can I count the number of> --> Tony> _____________________> amendes@math.ucsd.edu>> ==== Carl,Pushing your idea a bit further and avoiding one Drop and a subtraction oflists: w=Table[Random[Integer],{1000000}]; Tr[Drop[w,-1](Drop[w,-1]-Drop[w,1])]//Timing {7.85 Second,249850} (Tr[#]-Tr[# Drop[w,1]])&[Drop[w,-1] ]//Timing {2.75 Second,249850}--Allan---------------------Allan HayesMathematica Training and ConsultingLeicester UKwww.haystack.demon.co.ukhay@haystack.demon.co.ukVoice : +44 (0)116 271 4198> Anthony and newsgroup,>> I thought of another method of solving this problem which is 5 or 6times> faster than my previous version. Here is a test case.>> tst=Table[Random[Integer],{1000000}];>> My first solution was>> In[16]:=> Count[Partition[tst,2,1],{1,0}]//Timing> Out[16]=> {0.704 Second, 249722}>> My second solution is>> In[17]:=> Tr[Drop[tst,-1](Drop[tst,-1]-Drop[tst,1])]//Timing> Out[17]=> {0.125 Second, 249722}>> Carl Woll> Physics Dept> U of Washington> Suppose w={1,1,1,0,0,1,0,1,0,0,1,0,0}.>> How can I count the number of occurrences of a 1 in w immediately> followed by a 0 in w?>> I have tried every incarnation of Count[] I can think of; for example,>> Count[w,{___,1,0,___}]>> does not seem to work. In general, how can I count the number of> --> Tony> _____________________> amendes@math.ucsd.edu> ==== Arnold,The explanation for the difference in results when using Integrate versusNIntegrate lies in how the answers are computed.The function NIntegrate typically samples the integrand at a sufficientnumber of points to approximate the answer, using a strategy similar to butmore sophisticated than the trapezoidal approximation. In general,NIntegrate will always get the correct answer, although it is possible thatthe answer produced by NIntegrate may not be very precise.The function Integrate, on the other hand, basically does what you or Iwould do. It tries to find the antiderivative of the integrand, and then, ifthere are limits involved, those limits are plugged into the antiderivative.Usually, this procedure works perfectly well, and the correct answer isproduced. However, consider the case where the antiderivative has multiplebranches. Then, Integrate must use the same branch when plugging in thelimits into the integrand in order to produce the correct answer. Sometimes,Integrate will choose one branch for the upper limit, and a different branchfor the lower limit. When this happens, Integrate will get the wrong answer.The message you should get from the above discussion is that whenever youwant to compute a DEFINITE integral using Integrate, you should be awarethat the resulting answer may be incorrect if the antiderivative of theintegrand has multiple branches. On the other hand, for definite integrals,NIntegrate should always produce the correct answer. In other words, anytime you are trying to compute a definite integral with Integrate, and theintegrand looks complex, you probably should verify the answer usingNIntegrate.Carl WollPhysics DeptU of Washington> Here's a slightly simplified version of the integration problem Ipresented the other day:>> int=Integrate[UnitStep[1 - t^2 - c^2*(-4*t + 8*t^3)^2], {t, -1, 1}];> int /. c->0 Result:2> int /. c->0. Result:0.> int /. c->3 Result:2> int /. c->3. Result:0.28817>> In fact, int /. c-> any rational always yields 2!!!>> NIntegrate gets the right answers:> NIntegrate[UnitStep[1 - t^2 - 0^2*(-4*t + 8*t^3)^2], {t, -1, 1},> MinRecursion->5,MaxRecursion->30] Result: 2>> NIntegrate[UnitStep[1 - t^2 - 2^2*(-4*t + 8*t^3)^2], {t, -1, 1},> MinRecursion->5,MaxRecursion->30] Result: 0.28817>> Plot[int,{c,-5,5}] also gets the right results.>> Any help or insight into why Integrate isn't working would be greatlyappreciated!>> Greg> ==== Needs[Graphics`Arrow`]Plot[Sin[x], {x, 0, 2Pi}, Epilog -> {Arrow[{0, 0}, {7, 0}, HeadCenter -> 0.5], Arrow[{0, 0}, {0, 1.2}, HeadCenter -> 0.5]}, PlotRange -> {{0, 7}, {-1.1, 1.2}}];David Parkdjmp@earthlink.nethttp://home.earthlink.net/~djmp/ Approved: Steven M. Christensen , Moderator ==== Bob,Here is one approach.Attributes[set] = {Orderless};set[d, e, f, a, b, c] givesset[a, b, c, d, e, f]For some test data...set1 = set[d, e, f, g];set2 = set[a, b, c, d, e];set12 = Union[set1, set2]set[a, b, c, d, e, f, g]Here are the SubsetQ and SubsetEqualQ routines. (The real mathematicianswill probably have to check if I've captured all the subtleties of sets.)SubsetQ::usage = SubsetQ[set1, set2] returns True if set1 is a subset of set2.;SubsetQ[set1_set, set2_set] := Intersection[set2, set1] === set1 || set1 === set[];SubsetEqualQ::usage = SubsetEqualQ[set1, set2] returns True if set1 is equal to set2.;SubsetEqualQ[set1_set, set2_set] := SubsetQ[set1, set2] && SubsetQ[set2, set1];SubsetQ[set[a], set1]FalseSubsetQ[set[a, d, c], set12]TrueSubsetQ[set[], set12]TrueSubsetEqualQ[set[e, d, g, f], set1]TrueSubsetEqualQ[set[d, e, f], set1]FalseDavid Parkdjmp@earthlink.nethttp://home.earthlink.net/~djmp/ Sender: steve@smc.vnet.netApproved: Steven M. Christensen , Moderator ==== is seemingly a very simple problem .... The beep for an error worked on myfirst day of learning Mathematica, but today (day 2) all I get is the pop-upwindowabout the, not the beep. How can I get my beep back? Tom ==== Having quickly glanced through the avalanche of proposed solutions I did not see following one.(if there was I apologize for claiming it as my own):Count[w - RotateLeft[w], 1]According to my comparisons it is the fastest so far (the one that I sent originally is one of the slowest) In[1]:=w=Table[Random[Integer],{200000}];In[2]:=Count[ Partition[w,2,1],{1,0}]//TimingOut[2]={0.86 Second,50131}In[3]:=Count[Drop[w,-1]-Drop[w,1],1]//Timing Out[3]={0.34 Second,50131}In[5]:=Count[w-RotateLeft[w],1]//TimingOut[5 ]={0.29 Second,50131}Andrzej KozlowskiToyama International UniversityJAPANhttp://platon.c.u-tokyo.ac.jp/andrzej/> [second posting in view of reported technical problem]>> Anthony,> Take> w = Table[Random[Integer], {200000}>> My first thought was, and several posts used this,>> Count[Partition[w, 2,1],{1,0}]//Timing>> {3.24 Second,49851}>> Later it occured to me to use arithmetic, which turned out to be twice > as> fast:>> Count[ Drop[w,-1] - Drop[w,1],1]//Timing>> {1.49 Second,49851}>> This is close to Selwyn Hollis's code>> Count[Drop[w+2RotateRight[w],1],2]//Timing>> {1.6 Second,49851}>> --> 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>> Suppose w={1,1,1,0,0,1,0,1,0,0,1,0,0}.>> How can I count the number of occurrences of a 1 in w immediately>> followed by a 0 in w?>> I have tried every incarnation of Count[] I can think of; for example,>> Count[w,{___,1,0,___}]>> does not seem to work. In general, how can I count the number of>> you!>> -->> Tony>> _____________________>> amendes@math.ucsd.edu>> ==== I was too quick with sending my alleged solution , not noticing immediately that it fails in cases when w is of the form {0,...,1}. (It works however if we consider cyclic solutions, meaning that {0,1} is thought to contain one instance of {1,0}!)Since there seems no way of dealing with this problem without making the solutions slower, Alan'sCount[Drop[w,-1]-Drop[w,1],1]is indeed (almost certainly) the fastest solution.(of course one can still make it faster by compiling:f = Compile[{{w, _Integer, 1}}, Count[Drop[w, -1] - Drop[w, 1], 1]]is about 6 times faster on my machine than the uncompiled version).Andrzej> Having quickly glanced through the avalanche of proposed solutions I > did not see following one.(if there was I apologize for claiming it as > my own):>> Count[w - RotateLeft[w], 1]>> According to my comparisons it is the fastest so far (the one that I > sent originally is one of the slowest)>> In[1]:=> w=Table[Random[Integer],{200000}];>> In[2]:=> Count[Partition[w,2,1],{1,0}]//Timing>> Out[2]=> {0.86 Second,50131}>> In[3]:=> Count[Drop[w,-1]-Drop[w,1],1]//Timing>> Out[3]=> {0.34 Second,50131}>> In[5]:=> Count[w-RotateLeft[w],1]//Timing>> Out[5]=> {0.29 Second,50131}>Andrzej KozlowskiToyama International UniversityJAPANhttp://platon.c.u-tokyo.ac.jp/andrzej/>> > [second posting in view of reported technical problem]>> Anthony,>> Take>> w = Table[Random[Integer], {200000}>> My first thought was, and several posts used this,>> Count[Partition[w, 2,1],{1,0}]//Timing>> {3.24 Second,49851}>> Later it occured to me to use arithmetic, which turned out to be twice >> as>> fast:>> Count[ Drop[w,-1] - Drop[w,1],1]//Timing>> {1.49 Second,49851}>> This is close to Selwyn Hollis's code>> Count[Drop[w+2RotateRight[w],1],2]//Timing>> {1.6 Second,49851}>> -->> 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>> Suppose w={1,1,1,0,0,1,0,1,0,0,1,0,0}.>> How can I count the number of occurrences of a 1 in w immediately> followed by a 0 in w?>> I have tried every incarnation of Count[] I can think of; for example,>> Count[w,{___,1,0,___}]>> does not seem to work. In general, how can I count the number of> you!> --> Tony> _____________________> amendes@math.ucsd.edu> ==== David,Here is a function that lets us do this to an already created graphics.One of the catches that code deals with is that unless we specify PlotRangenumerically Mathematica will choose its own PlotRange that cannot bepredicted in advance.Also, I use a trick to load the package Graphics`Arrow at the right stagewhen the function is entered and so that it will not be seen by a user when?AddArrowsOnAxes is entered. AddArrowsToAxes[gr_, Needs[Graphics`Arrow`] /. _ -> Sequence[], opts___?OptionQ] := Module[{oxx, oyy, xxmin, xxmax, yymin, yymaxx, xxst, yyst, Arrow = Graphics`Arrow`Arrow }, {{oxx, oyy}, {{xxmin, xxmax}, {yymin, yymax}}, {xxst, yyst}} = Last /@ AbsoluteOptions[ Graphics[gr], {AxesOrigin, PlotRange, AxesStyle}]; Show[gr, Prolog -> {Append[xxst, Arrow[{xxmin, oyy}, {xxmax, oyy}, opts]], Append[yyst, Arrow[{oxx, yymin}, {oxx, yymax}, opts]]}] ];Test: AddArrowsToAxes[gr1,HeadCenter->0.7] ; AddArrowsToAxes[gr1,Graphics`Arrow`HeadCenter->0.7] ;--Allan---------------------Allan HayesMathematica Training and ConsultingLeicester UKwww.haystack.demon.co.ukhay@haystack.demon.co.ukVoice : +44 (0)116 271 4198> How do I put Arrow Heads on the ends of the Axis of my plots?>> ==== > How do I put Arrow Heads on the ends of the Axis of my plots?Dear barnes: The command Arrow can be used to draw an arrow.But it is in thepackage of Graphics . We can draw the arrow on the ends of axis bythis way :Input[1]: Needs[Graphics`Arrow`] Plot[Sin[x], {x, -Pi, Pi}, Epilog -> {Arrow[{2, 0}, {1.05Pi, 0}], Arrow[{0, 0}, {0,1.05}]}] ==== Thomas,Bring up the Option Inspector to set preferences for your system. You can dothis with Shift-Ctrl-O, or from EditPreferences in the menu, or fromFormatOption Inspector in the menu.Show the option values for global. Under Global OptionsMessage Options makecertain that Beep is present for the various types of messages. Click on theright hand button and then click Beep to check it.Also check that your speakers are on.David Parkdjmp@earthlink.nethttp://home.earthlink.net/~djmp/ Sender: steve@smc.vnet.netApproved: Steven M. Christensen , Moderator ==== For[i = 1, i < 10, i++, Show[Graphics[Point[{i, i}]]]]This genereates nine graphics with one point each. I was trying togenerate one graphic with nine points. I see my problem as callingthe Point function nine times instead of only once. I wish to use thedata generated by the loop on a single graphic.P.S. In the end I will be doing three For loops in a nested formationto generate the data to put on one graphic.-Michael ==== > For[i = 1, i < 10, i++, Show[Graphics[Point[{i, i}]]]]> This genereates nine graphics with one point each. I was trying to> generate one graphic with nine points. I see my problem as calling> the Point function nine times instead of only once. I wish to use the> data generated by the loop on a single graphic.It looks as if you are coming from an imperative programming background.Is the for loop a must?Here is a suggestion on a functional solution:Show[Graphics[Point[{#1, #1}] & /@ Range[1, 9]]]i assume you are not familiar with some of the expressions above. evaluate:Range[1, 9]this returns a list with numbers 1 to 9.now Point[{#1, #1}] & is a pure function. this means a function without aname. usually you would write something like a = 1 + iwith a pure function you write (1 + #1)& here #1 takes the job of i andthe & is to denote that we are dealing with a pure function. to put some values into #1 you could map them. this is what the /@ does.so we map the result from Range[1,9] onto the pure function Point[{#1,#1}]. to see that evaluate:Point[{#1, #1}] & /@ Range[1, 9]does this help ?Oliver Ruebenkoenig, ==== Michael, Try this:Show[Graphics[Table[Point[{i, i}], {i, 1, 10}]]]Brian> For[i = 1, i < 10, i++, Show[Graphics[Point[{i, i}]]]]> This genereates nine graphics with one point each. I was trying to> generate one graphic with nine points. I see my problem as calling> the Point function nine times instead of only once. I wish to use the> data generated by the loop on a single graphic.> P.S. In the end I will be doing three For loops in a nested formation> to generate the data to put on one graphic.> -MichaelReply-To: kuska@informatik.uni-leipzig.de ==== Show[Graphics[Table[ Point[{i, i}], {i, 10}]]]orShow[Graphics[Point [{#, #}] & /@ Range[10]]]if you prefer a stupid and useless construct like For[]Show[Graphics[ lst = {}; For[i = 1, i < 10, i++, AppendTo[lst, Point[{i, i}]]]; lst ]] Jens> For[i = 1, i < 10, i++, Show[Graphics[Point[{i, i}]]]]> This genereates nine graphics with one point each. I was trying to> generate one graphic with nine points. I see my problem as calling> the Point function nine times instead of only once. I wish to use the> data generated by the loop on a single graphic.> P.S. In the end I will be doing three For loops in a nested formation> to generate the data to put on one graphic.> -Michael ==== I want to thank all of you and to let this group know that I know thatthere are many skilled and helpful people attending this group. Ihave through the help of no less than six people been given vast anddetailed information concerning the problem I had.-MichaelP.S. Here is the final graphic I was trying to produce. It is part ofa infinite array :)Show[Graphics[Table[Point[{x,y}],{n,2,100},{x,1,100,n},{y, 1,100,n}]]]; ==== options are set properly. Actually, in my original message I should have saidthat I had done that check -- beep is on in all conditions, probably thedefault. Also, my speakers are on (and are working in an independent check). Maybe I need to uninstall and reinstall, but I'll wait a while longer tosee if anyone may have a clue as to what happened. Tom--On Sunday, July 21, 2002 8:56 AM -0400 David Park Thomas,>> Bring up the Option Inspector to set preferences for your system. You can> do this with Shift-Ctrl-O, or from EditPreferences in the menu, or from> FormatOption Inspector in the menu.>> Show the option values for global. Under Global OptionsMessage Options> make certain that Beep is present for the various types of messages.> Click on the right hand button and then click Beep to check it.>> Also check that your speakers are on.>> David Park> djmp@earthlink.net> http://home.earthlink.net/~djmp/>> what is seemingly a very simple problem .... The beep for an error worked> on my first day of learning Mathematica, but today (day 2) all I get is> the pop-up window> about the, not the beep. How can I get my beep back? Tom> ==== About not hearing the beep: the options are set for beep in all conditionsand my speakers are working. ==== Adding Andrzej's idea using a single rotation with correction to Carl'slatest gives a further speed up: w=Table[Random[Integer],{1000000}]; (Tr[#]-Tr[BitAnd[# ,Drop[w,1]]])&[Drop[w,-1] ]//Timing {2.36 Second,249981} (Tr[w]-Tr[BitAnd[w ,RotateLeft[w]]])+ If[w[[1]]==0&&w[[-1]]==1,-1,0]//Timing {1.43 Second,249981}--Allan---------------------Allan HayesMathematica Training and ConsultingLeicester UKwww.haystack.demon.co.ukhay@haystack.demon.co.ukVoice : +44 (0)116 271 4198 ==== Allan,One further small tweak.Your refinement:s1[w_] := (Tr[#1] - Tr[#1 Drop[w, 1]] & )[Drop[w, -1]]My tweak is to use BitAnd instead of multiplication:s2[w_] := (Tr[#1] - Tr[BitAnd[#1, Drop[w, 1]]] & )[Drop[w, -1]]Testing:tst = Table[Random[Integer], {10^7}];In[4]:=s1[tst]//Timings2[tst]//TimingOut[4]={ 0.641 Second, 2498910}Out[5]={0.5 Second, 2498910}So, BitAnd appears to be slightly faster.Carl WollPhysics DeptU of Washington----- Original Message -----> {7.85 Second,249850}>> (Tr[#]-Tr[# Drop[w,1]])&[Drop[w,-1] ]//Timing>> {2.75 Second,249850}>> --> 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> Anthony and newsgroup,>> I thought of another method of solving this problem which is 5 or 6> times> faster than my previous version. Here is a test case.>> tst=Table[Random[Integer],{1000000}];>> My first solution was>> In[16]:=> Count[Partition[tst,2,1],{1,0}]//Timing> Out[16]=> {0.704 Second, 249722}>> My second solution is>> In[17]:=> Tr[Drop[tst,-1](Drop[tst,-1]-Drop[tst,1])]//Timing> Out[17]=> {0.125 Second, 249722}>> Carl Woll> Physics Dept> U of Washington> Suppose w={1,1,1,0,0,1,0,1,0,0,1,0,0}.>> How can I count the number of occurrences of a 1 in w immediately> followed by a 0 in w?>> I have tried every incarnation of Count[] I can think of; for example,>> Count[w,{___,1,0,___}]>> does not seem to work. In general, how can I count the number ofyou!> --> Tony> _____________________> amendes@math.ucsd.edu>> ==== It now seems to me that I was again premature in stating that Allan's solution is the fastest possible. In fact one can construct a hybrid solution made of my faulty (cyclic) solution and Allan's solution which will be on the average faster. Since the cyclic solution fails only in cases when the first digit is 0 and the last 1, we use it in all the other cases and switch to Allan's in the unfavorable ones. The pattern matching needed to do that will cause a slight loss of speed but still we will be faster on about 3/4 of cases (very slightly of course). Here is what actually happens:Here is Allan's solution:g[l_List] := Count[Drop[l, -1] - Drop[l, 1], 1];here is the hybrid one:f[l_List] /; Last[l] .89.81æ 1 && First[l] .89.81æ 0 := Count[l - RotateLeft[l], 1];f[l_List] := Count[Drop[l, -1] - Drop[l, 1], 1];here is our random test generator:w := Table[Random[Integer], {2000}]We now see the difference in time used over a 1000 random test runs:In[5]:=Block[{x},Plus@@Table[Timing[x=w;(g[x]-f[x])],{ 1000}]]Out[5]={7.32 Second,0}Andrzej KozlowskiToyama International UniversityJAPANhttp://platon.c.u-tokyo.ac.jp/andrzej/> I was too quick with sending my alleged solution , not noticing > immediately that it fails in cases when w is of the form {0,...,1}. > (It works however if we consider cyclic solutions, meaning that {0,1} > is thought to contain one instance of {1,0}!)>> Since there seems no way of dealing with this problem without making > the solutions slower, Alan's>> Count[Drop[w,-1]-Drop[w,1],1]>> is indeed (almost certainly) the fastest solution.>> (of course one can still make it faster by compiling:>> f = Compile[{{w, _Integer, 1}}, Count[Drop[w, -1] - Drop[w, 1], 1]]>> is about 6 times faster on my machine than the uncompiled version).>> Andrzej> Having quickly glanced through the avalanche of proposed solutions I >> did not see following one.(if there was I apologize for claiming it as >> my own):>> Count[w - RotateLeft[w], 1]>> According to my comparisons it is the fastest so far (the one that I >> sent originally is one of the slowest)>> In[1]:=>> w=Table[Random[Integer],{200000}];>> In[2]:=>> Count[Partition[w,2,1],{1,0}]//Timing>> Out[2]=>> {0.86 Second,50131}>> In[3]:=>> Count[Drop[w,-1]-Drop[w,1],1]//Timing>> Out[3]=>> {0.34 Second,50131}>> In[5]:=>> Count[w-RotateLeft[w],1]//Timing>> Out[5]=>> {0.29 Second,50131}> [second posting in view of reported technical problem]>> Anthony,> Take> w = Table[Random[Integer], {200000}>> My first thought was, and several posts used this,>> Count[Partition[w, 2,1],{1,0}]//Timing>> {3.24 Second,49851}>> Later it occured to me to use arithmetic, which turned out to be > twice as> fast:>> Count[ Drop[w,-1] - Drop[w,1],1]//Timing>> {1.49 Second,49851}>> This is close to Selwyn Hollis's code>> Count[Drop[w+2RotateRight[w],1],2]//Timing>> {1.6 Second,49851}>> --> 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>> Suppose w={1,1,1,0,0,1,0,1,0,0,1,0,0}.>> How can I count the number of occurrences of a 1 in w immediately>> followed by a 0 in w?>> I have tried every incarnation of Count[] I can think of; for >> example,>> Count[w,{___,1,0,___}]>> does not seem to work. In general, how can I count the number of>> you!>> -->> Tony>> _____________________>> amendes@math.ucsd.edu>>=== =1) Working with Mathematica 4.1 on a Mac iBook running OS 9.1 I've recently been encountering repeated situations where, after working with any one of a collection of several different small notebooks for a short time, and perhaps causing some errors, I get a dialog box that says There was not enough memory to display a cell. The cell has been closed. When you have freed some memory you can open it again by choosing Cell Open the the Cell Properties menu.Clicking OK just brings up the box again in an endless loop; doing a Force Quit usually leads to a crash. The notebooks are only a dozen cells or so long. I've increased Mathematica's memory allocation; no help.Is this some kind of memory leak, or . . . ?2) Possibly related: I have a My Mathematica Notes notebook -- a kind of personalized Help file -- in which I collect misc notes, useful snippets of Mathematica code in the form of Input cells, other examples I've seen on this group or elsewhere. It's about 140K in size. I'm not sure but I think the above problem may sometimes occur shortly after I open this Notes notebook to copy a cell out of it.I don't want to run or execute any cells in this notebook, ever. Are there some options or defaults I should set so that none of the Input cells in this notebook will execute while it's open, yet I can copy and paste them as executable Input cells in another notebook I'm working on? ==== > 1) Working with Mathematica 4.1 on a Mac iBook running OS 9.1 I've recently > been encountering repeated situations where, after working with any one > of a collection of several different small notebooks for a short time, > and perhaps causing some errors, I get a dialog box that says> There was not enough memory to display a cell. The cell has> been closed. When you have freed some memory you can open> it again by choosing Cell Open the the Cell Properties menu.I'll let a Mac guru answer this one.> I don't want to run or execute any cells in this notebook, ever. Are > there some options or defaults I should set so that none of the Input > cells in this notebook will execute while it's open, yet I can copy and > paste them as executable Input cells in another notebook I'm working on?You could set the Evaluator for the notebook to None. Open thenotebook in the FrontEnd, make sure it is the current notebook, then--Bhuvanesh,Wolfram Research. ==== There's an FAQ on issue #1 at http://support.wolfram.com/mathematica/systems/macintosh/ general/doublebuffer.html(This problem annoyed me for many months.)---Selwyn> 1) Working with Mathematica 4.1 on a Mac iBook running OS 9.1 I've recently > been encountering repeated situations where, after working with any one > of a collection of several different small notebooks for a short time, > and perhaps causing some errors, I get a dialog box that says> There was not enough memory to display a cell. The cell has> been closed. When you have freed some memory you can open> it again by choosing Cell Open the the Cell Properties menu.> Clicking OK just brings up the box again in an endless loop; doing a > Force Quit usually leads to a crash. The notebooks are only a dozen > cells or so long. I've increased Mathematica's memory allocation; no help.> Is this some kind of memory leak, or . . . ?> 2) Possibly related: I have a My Mathematica Notes notebook -- a kind of > personalized Help file -- in which I collect misc notes, useful snippets > of Mathematica code in the form of Input cells, other examples I've seen on this > group or elsewhere. It's about 140K in size. I'm not sure but I think > the above problem may sometimes occur shortly after I open this Notes > notebook to copy a cell out of it.> I don't want to run or execute any cells in this notebook, ever. Are > there some options or defaults I should set so that none of the Input > cells in this notebook will execute while it's open, yet I can copy and > paste them as executable Input cells in another notebook I'm working on?> Reply-To: ==== Selwyn's code is almost always a little faster than Allan's (though notmuch). The difference is around 4% for lists of 2,000,000 entries.Here are results for thirty trials of the two arithmetic methods, with 2million entries each time, using a paired t-test:Needs[Statistics`HypothesisTests`]f1[w_]:=Count[ Partition[w, 2,1],{1,0}]f2[w_]:=Count[Drop[w,-1] - Drop[w,1],1]f3[w_]:=Count[Drop[w+2RotateRight[w],1],2]trial :=(n=2000000;w = Table[Random[Integer], {n}];First@Timing[#[w];]/Second&/@{f2,f3} ){t1, t2} = Transpose[(trial & ) /@ Range[30]]; Mean /@ {t1, t2}r = MeanTest[t1 - t2, 0, FullReport -> True]meanDiff = (FullReport /. r)[[1,1,1]]; Print[% difference = , meanDiff/Mean[t1]]{0.5864333333333358, 0.5621333333333306}{FullReport -> TableForm[ {{Mean, TestStat, Distribution}, {0.024300000000005186, 3.3246821117809677, StudentTDistribution[ 29]}}, TableHeadings -> {None, {Mean, TestStat, Distribution}}], OneSidedPValue -> 0.0012041503843005326}% difference = 0.0414369351That's a 4% difference and a p-value of about 0.1%.Bobby Treat-----Original Message-----asfast: Count[ Drop[w,-1] - Drop[w,1],1]//Timing {1.49 Second,49851}This is close to Selwyn Hollis's code Count[Drop[w+2RotateRight[w],1],2]//Timing {1.6 Second,49851}--Allan---------------------Allan HayesMathematica Training and ConsultingLeicester UKwww.haystack.demon.co.ukhay@haystack.demon.co.ukVoice : +44 (0)116 271 4198>> Suppose w={1,1,1,0,0,1,0,1,0,0,1,0,0}.>> How can I count the number of occurrences of a 1 in w immediately> followed by a 0 in w?>> I have tried every incarnation of Count[] I can think of; for example,>> Count[w,{___,1,0,___}]>> does not seem to work. In general, how can I count the number ofyou!> --> Tony> _____________________> amendes@math.ucsd.edu>>Reply-To: ==== Wow, Carl! That's about three times as fast as Selwyn's code!Needs[Statistics`HypothesisTests`]f1[w_]:=Count[ Partition[w, 2,1],{1,0}]f2[w_]:=Count[Drop[w,-1] - Drop[w,1],1]f3[w_]:=Count[Drop[w+2RotateRight[w],1],2]f4[w_ ]:=Tr[Drop[w,-1](Drop[w,-1]-Drop[w,1])]trial:=(n=2000000;w = Table[Random[Integer], {n}]; First@Timing[#[w];]/Second&/@{f3,f4} ){t1,t2}=Transpose[trial&/@Range[30]];Mean/@{t1,t2}r= MeanTest[t1-t2,0,FullReport[Rule]True]meanDiff=(FullReport /.r)[[1,1,1]];Print[% difference = ,meanDiff/Mean[t1]]{0.560933, 0.2105}{FullReport -> TableForm[ {{Mean, TestStat, Distribution}, {0.35043333333333826, 44.64543969496886, StudentTDistribution[29]}}, TableHeadings -> {None, {Mean, TestStat, Distribution}}], OneSidedPValue -> 1.377763589983338*^-28}% difference = 0.6247325885429081That's 62% less time spent, with a p-value of about 10^-28.Bobby-----Original Message-----Out[16]={0.704 Second, 249722}My second solution isIn[17]:=Tr[Drop[tst,-1](Drop[tst,-1]-Drop[tst,1])]// TimingOut[17]={0.125 Second, 249722}Carl WollPhysics DeptU of Washington>> Suppose w={1,1,1,0,0,1,0,1,0,0,1,0,0}.>> How can I count the number of occurrences of a 1 in w immediately> followed by a 0 in w?>> I have tried every incarnation of Count[] I can think of; for example,>> Count[w,{___,1,0,___}]>> does not seem to work. In general, how can I count the number ofyou!> --> Tony> _____________________> amendes@math.ucsd.edu>> ==== Dear experts, How can I force mathemathica41 to make graphics in a column of same width but different height? By default, mathematica gives two cells on top of each other the same height, but arranges the width such that both cells fit in the column width. This results in a horizontal sequeezing/scaling of cells which I would like to omit. Here is an example: Single output of both plots one after to the other just looks fine, but when they enter in an GraphicsArray[], the automatic scaling squeezes the lower cell width instead of stretching its height. >> demo start : just cut and paste into a new .nb >> !((( (* demo starts here *) )([IndentingNewLine])(()([IndentingNewLine]) (table1 = ListPlot3D[ Table[Sin[x y], {x, 0, (3 Pi)/2, Pi/15}, {y, 0, (3 Pi)/2, Pi/15}], PlotRange -> {0, 0.25}, Axes -> {None, None, None}, ViewPoint -> {5, (-2.5), 0.6}, BoxRatios -> {10, 10, 1.25}];)([IndentingNewLine]) (table2 = ListPlot3D[ Table[Sin[x y], {x, 0, (3 Pi)/2, Pi/15}, {y, 0, (3 Pi)/2, Pi/15}], PlotRange -> {(-1), 0}, Axes -> {None, None, None}, ViewPoint -> {5, (-2.5), 1}, BoxRatios -> {10, 10, 5}];)([IndentingNewLine]) ()( [IndentingNewLine]) (table3 = {{table1}, {table2}};)([IndentingNewLine]) (Show[GraphicsArray[ table3, GraphicsSpacing -> 0]];)([IndentingNewLine]) ()([IndentingNewLine]) ( (* demo ends here*) )))) >> demo end >> Playing around with TableForm[] or RowsEqual-> or ImageSize-> didn't help so far. For all those of you that might have similar problems with plotting graphics: there are good support-procedures on the David-Park-homepage http://home.earthlink.net/~djmp/Mathematica.html But I couldn't find a solution for my problem. My general purpose is to generate an animated GIF, which shows a 360-degree-ßy-around a surface plot, that is cut into two parts at some z-value (this visualizes threshold effects on surfaces). Interested people can get a copy of my *.nb I carefully browsed through TMB and F1HELP for GraphicsArray-Options (well I think that F1 is pretty poor on these specific subjects), and of course also this newsgroup, but I couln't find the magic trick sought for. Bye StefReply-To: kuska@informatik.uni-leipzig.de ==== fix the AspectRatio to the same value for both plots, i. e.,table1 = ListPlot3D[Table[Sin[x*y], {x, 0, (3*Pi)/2, Pi/15}, {y, 0, (3*Pi)/2, Pi/15}], PlotRange -> {0, 0.25}, Axes -> {None, None, None}, ViewPoint -> {5, -2.5, 0.6}, BoxRatios -> {10, 10, 1.25}, AspectRatio -> 1/2]; table2 = ListPlot3D[Table[Sin[x*y], {x, 0, (3*Pi)/2, Pi/15}, {y, 0, (3*Pi)/2, Pi/15}], PlotRange -> {-1, 0}, Axes -> {None, None, None}, ViewPoint -> {5, -2.5, 1}, BoxRatios -> {10, 10, 5}, AspectRatio -> 1/2]; Jens> Dear experts,> How can I force mathemathica41 to make graphics in a column of same> width but different height?> By default, mathematica gives two cells on top of each other the same> height, but arranges the width such that both cells fit in the column> width.> This results in a horizontal sequeezing/scaling of cells which I would> like to omit.> Here is an example:> Single output of both plots one after to the other just looks fine,> but when they enter in an GraphicsArray[], the automatic scaling> squeezes the lower cell width instead of stretching its height.>> demo start : just cut and paste into a new .nb > !((( (*> demo starts here *) )([IndentingNewLine])(( plots > are shown here:>)([IndentingNewLine])> (table1 => ListPlot3D[> Table[Sin[x y], {x, 0, (3 Pi)/2, Pi/15}, {y, 0, (3> Pi)/2,> Pi/15}], PlotRange -> {0, 0.25},> Axes -> {None, None, None}, > ViewPoint -> {5, (-2.5), 0.6},> BoxRatios -> {10, 10, 1.25}];)([IndentingNewLine])> (table2 = > ListPlot3D[> Table[Sin[x y], {x, 0, (3 Pi)/2, Pi/15}, {y, 0, (3> Pi)/2,> Pi/15}], PlotRange -> {(-1), 0}, > Axes -> {None, None, None},> ViewPoint -> {5, (-2.5), 1},> BoxRatios -> {10, 10, 5}];)([IndentingNewLine])> ( graphicsarray:>)(> [IndentingNewLine])> (table3 = {{table1}, {table2}};)([IndentingNewLine])> (Show[GraphicsArray[> table3, GraphicsSpacing -> > 0]];)([IndentingNewLine])> ( width > (but different height) ? Mathematicas default is: same height, but> different > widths.>)([IndentingNewLine])> ( (* demo ends here*) ))))>> demo end > Playing around with TableForm[] or RowsEqual-> or ImageSize-> didn't> help so far. For all those of you that might have similar problems> with plotting graphics:> there are good support-procedures on the David-Park-homepage> http://home.earthlink.net/~djmp/Mathematica.html> But I couldn't find a solution for my problem.> My general purpose is to generate an animated GIF, which shows a> 360-degree-ßy-around a surface plot, that is cut into two parts> at some z-value (this visualizes threshold effects on surfaces).> Interested people can get a copy of my *.nb> I carefully browsed through TMB and F1HELP for GraphicsArray-Options> (well I think that F1 is pretty poor on these specific subjects),> and of course also this newsgroup, but I couln't find the magic trick> sought for.> > Bye> Stef ==== Stef,Instead of GraphicsArray put your graphics into Rectangles of appropriatepositions, sizes, and shapes (apect ratio close to that of the containedgraphic) and Show them together.--Allan---------------------Allan HayesMathematica Training and ConsultingLeicester UKwww.haystack.demon.co.ukhay@haystack.demon.co.ukVoice : +44 (0)116 271 4198> Dear experts,>> How can I force mathemathica41 to make graphics in a column of same> width but different height?> By default, mathematica gives two cells on top of each other the same> height, but arranges the width such that both cells fit in the column> width.> This results in a horizontal sequeezing/scaling of cells which I would> like to omit.>> Here is an example:> Single output of both plots one after to the other just looks fine,> but when they enter in an GraphicsArray[], the automatic scaling> squeezes the lower cell width instead of stretching its height.>> demo start : just cut and paste into a new .nb >> !((( (*> demo starts here *) )([IndentingNewLine])(( plots > are shown here:>)([IndentingNewLine])> (table1 => ListPlot3D[> Table[Sin[x y], {x, 0, (3 Pi)/2, Pi/15}, {y, 0, (3> Pi)/2,> Pi/15}], PlotRange -> {0, 0.25},> Axes -> {None, None, None}, > ViewPoint -> {5, (-2.5), 0.6},> BoxRatios -> {10, 10, 1.25}];)([IndentingNewLine])> (table2 = > ListPlot3D[> Table[Sin[x y], {x, 0, (3 Pi)/2, Pi/15}, {y, 0, (3> Pi)/2,> Pi/15}], PlotRange -> {(-1), 0}, > Axes -> {None, None, None},> ViewPoint -> {5, (-2.5), 1},> BoxRatios -> {10, 10, 5}];)([IndentingNewLine])> ( graphicsarray:>)(> [IndentingNewLine])> (table3 = {{table1}, {table2}};)([IndentingNewLine])> (Show[GraphicsArray[> table3, GraphicsSpacing -> > 0]];)([IndentingNewLine])> ( width > (but different height) ? Mathematicas default is: same height, but> different > widths.>)([IndentingNewLine])> ( (* demo ends here*) ))))> demo end >> Playing around with TableForm[] or RowsEqual-> or ImageSize-> didn't> help so far. For all those of you that might have similar problems> with plotting graphics:> there are good support-procedures on the David-Park-homepage> http://home.earthlink.net/~djmp/Mathematica.html> But I couldn't find a solution for my problem.> My general purpose is to generate an animated GIF, which shows a> 360-degree-ßy-around a surface plot, that is cut into two parts> at some z-value (this visualizes threshold effects on surfaces).> Interested people can get a copy of my *.nb>> I carefully browsed through TMB and F1HELP for GraphicsArray-Options> (well I think that F1 is pretty poor on these specific subjects),> and of course also this newsgroup, but I couln't find the magic trick> sought for.> Bye> Stef>Reply-To: ==== Amazing! f5 is three times as fast as the previous best (f4), which wasthree times as fast as f3:Needs[Statistics`HypothesisTests`]f1[w_] := Count[Partition[w, 2, 1], {1, 0}]f2[w_] := Count[Drop[w, -1] - Drop[w, 1], 1]f3[w_] := Count[Drop[w + 2RotateRight[w], 1], 2]f4[w_] := Tr[Drop[w, -1](Drop[w, -1] - Drop[w, 1])]f5[w_] := (Tr[w] - Tr[BitAnd[w, RotateLeft[w]]]) + If[w[[ 1]] == 0 && w[[-1]] == 1, -1, 0]trial := (n = 2000000; w = Table[Random[Integer], {n}];First@Timing[#[w];]/Second & /@ {f4, f5} ){t1, t2} = Transpose[trial & /@ Range[30]];Mean /@ {t1, t2}r = MeanTest[t1 - t2, 0, FullReport -> True]meanDiff = (FullReport /. r)[[1, 1, 1]];Print[% difference = , meanDiff/Mean[t1]]{0.21470000000000045, 0.07439999999999972}{FullReport -> TableForm[ {{Mean, TestStat, Distribution}, {0.14030000000000073, 25.617955788393118, StudentTDistribution[29]}}, TableHeadings -> {None, {Mean, TestStat, Distribution}}], OneSidedPValue -> 9.108095822591074*^-22}% difference = 0.6534699580Bobby Treat-----Original Message-------Allan---------------------Allan HayesMathematica Training and ConsultingLeicester UKwww.haystack.demon.co.ukhay@haystack.demon.co.ukVoice : +44 (0)116 271 4198 ==== I suspect the problem you're seeing is not a memory leak, although itexhibits the similar (but not identical) symptoms. On Macintosh OS'sprevious to MacOS X, the primitive memory management methods availablemake applications much more subject to problems with memory fragmentationthen modern OS's like MacOS X, Unix, and Windows operating systems.Memory fragmentation can leave a program in a state where there's lotsof room to allocate small blocks of memory, but no room to allocatelarge blocks of memory. In Mathematica 4.1.0, there is one largeblock of memory which is frequently allocated and reallocated bydefault...it's used as a bitmap backing for the frontmost notebookwindow, and its frequent reallocation can contribute significantly tomemory fragmentation..Likely, the problem you're seeing results after a lot of notebook windowresizes and/or creation/deletion of notebook windows. The problemcan be worked around by opening up the Option Inspector (Format->OptionInspector...), setting the scope to global, and setting the DoubleBufferoption to False (just search for DoubleBuffer in the lookup field).It would be a good idea to restart after this. The only down side to thisis that you might notice slightly more ßicker during screen repaints.We fixed the fragmentation issue caused by this particular problem inMathematica 4.1.2, although you can never expect memory management tobe even remotely as robust as it would be under MacOS X.Concerning your second question, I suggest changing the stylesheeton your My Mathematica Notes notebook. ChooseFormat->Edit Style Sheet... and click the option to import a privatecopy. Find the group for the Input style, select the whole group, andchoose Cell->Cell Properties->Cell Evaluatable (which will uncheck theoption). Now close the styles notebook and re-save the My Mathematicashouldn't evaluate, but Input in every other notebook will continueto be evaluatable. The copy and paste will only transfer the Inputstylename, and inherit all of the properties of the Input stylein the appropriate notebook.Sincerely,John Fultzjfultz@wolfram.comUser Interface GroupWolfram Research, Inc.> 1) Working with Mathematica 4.1 on a Mac iBook running OS 9.1 I've recently > been encountering repeated situations where, after working with any one > of a collection of several different small notebooks for a short time, > and perhaps causing some errors, I get a dialog box that says> There was not enough memory to display a cell. The cell has> been closed. When you have freed some memory you can open> it again by choosing Cell Open the the Cell Properties menu.> Clicking OK just brings up the box again in an endless loop; doing a > Force Quit usually leads to a crash. The notebooks are only a dozen > cells or so long. I've increased Mathematica's memory allocation; no help.> Is this some kind of memory leak, or . . . ?> 2) Possibly related: I have a My Mathematica Notes notebook -- a kind of > personalized Help file -- in which I collect misc notes, useful snippets > of Mathematica code in the form of Input cells, other examples I've seen on this > group or elsewhere. It's about 140K in size. I'm not sure but I think > the above problem may sometimes occur shortly after I open this Notes > notebook to copy a cell out of it.> I don't want to run or execute any cells in this notebook, ever. Are > there some options or defaults I should set so that none of the Input > cells in this notebook will execute while it's open, yet I can copy and > paste them as executable Input cells in another notebook I'm working on? ==== Dear Michael,your most important problem is the strategy to useloops in Mathematica. My advice: don't.Unfortunately you didn't append your code consistingof four nested loops. Surely the problem can besolved without loops and becomes clearer and more readablethen.Here are three solutions for you problem:Show[Graphics[Table[Point[{i,i}],{i,10}]]]ListPlot[ Table[{i,i},{i,10}]]ListPlot[Range[10]]So please try to avoid loops in Mathematica.Loops produce long confusing code and slowdown evaluation time. Johannes Ludsteck > For[i = 1, i < 10, i++, Show[Graphics[Point[{i, i}]]]]> This genereates nine graphics with one point each. I was trying to> generate one graphic with nine points. I see my problem as calling> the Point function nine times instead of only once. I wish to use the> data generated by the loop on a single graphic.> P.S. In the end I will be doing three For loops in a nested formation> to generate the data to put on one graphic.> -Michael> <><><><><><><><><><><><><><><><><><>Johannes LudsteckInstitut fuer VolkswirtschaftslehreLehrstuhl Prof. Dr. MoellerUniversitaet RegensburgUniversitaetsstrasse 3193053 RegensburgReply-To: ==== f6 appears to be about twice as fast as f4:Needs[Statistics`HypothesisTests`]f1[w_] := Count[Partition[w, 2, 1], {1, 0}]f2[w_] := Count[Drop[w, -1] - Drop[w, 1], 1]f3[w_] := Count[Drop[w + 2RotateRight[w], 1], 2]f4[w_] := Tr[Drop[w, -1](Drop[w, -1] - Drop[w, 1])]f5[w_] := (Tr[w] - Tr[BitAnd[w, RotateLeft[w]]]) + If[w[[ 1]] == 0 && w[[-1]] == 1, -1, 0]f6[w_] := (Tr[#] - Tr[# Drop[w, 1]]) &[Drop[w, -1]]trial := (n = 2000000; w = Table[Random[Integer], {n}];First@Timing[#[w];]/Second & /@ {f4, f6} ){t1, t2} = Transpose[trial & /@ Range[30]];Mean /@ {t1, t2}r = MeanTest[t1 - t2, 0, FullReport -> True]meanDiff = (FullReport /. r)[[1, 1, 1]];Print[% difference = , meanDiff/Mean[t1]]{0.21726666666666658, 0.11146666666666712}{FullReport -> TableForm[ {{Mean, TestStat, Distribution}, {0.10579999999999945, 15.693202721924115, StudentTDistribution[29]}}, TableHeadings -> {None, {Mean, TestStat, Distribution}}], OneSidedPValue -> 5.207406739210963*^-16}% difference = 0.4869591899f5 is still about 1.5 times as fast as f6, though:trial := (n = 2000000; w = Table[Random[Integer], {n}];First@Timing[#[w];]/Second & /@ {f6, f5} )(same test code as above){0.09896666666666647, 0.0691333333333335}{FullReport -> TableForm[ {{Mean, TestStat, Distribution}, {0.029833333333332965, 5.308061210842354, StudentTDistribution[29]}}, TableHeadings -> {None, {Mean, TestStat, Distribution}}], OneSidedPValue -> 5.387889994701921*^-6}% difference = 0.3014482990Bobby Treat-----Original Message----- {2.75 Second,249850}--Allan---------------------Allan HayesMathematica Training and ConsultingLeicester UKwww.haystack.demon.co.ukhay@haystack.demon.co.ukVoice : +44 (0)116 271 4198> Anthony and newsgroup,>> I thought of another method of solving this problem which is 5 or 6times> faster than my previous version. Here is a test case.>> tst=Table[Random[Integer],{1000000}];>> My first solution was>> In[16]:=> Count[Partition[tst,2,1],{1,0}]//Timing> Out[16]=> {0.704 Second, 249722}>> My second solution is>> In[17]:=> Tr[Drop[tst,-1](Drop[tst,-1]-Drop[tst,1])]//Timing> Out[17]=> {0.125 Second, 249722}>> Carl Woll> Physics Dept> U of Washington> Suppose w={1,1,1,0,0,1,0,1,0,0,1,0,0}.>> How can I count the number of occurrences of a 1 in w immediately> followed by a 0 in w?>> I have tried every incarnation of Count[] I can think of; forexample,>> Count[w,{___,1,0,___}]>> > does not seem to work. In general, how can I count the number ofyou!> --> Tony> _____________________> amendes@math.ucsd.edu>> >> ==== >For[i = 1, i < 10, i++, Show[Graphics[Point[{i, i}]]]]>>This genereates nine graphics with one point each. I was trying to>generate one graphic with nine points. I see my problem as calling>the Point function nine times instead of only once. I wish to use the>data generated by the loop on a single graphic.>P.S. In the end I will be doing three For loops in a nested formation>to generate the data to put on one graphic.>Show[Graphics[Table[Point[{i,i}],{i,9}]]];Show[ Graphics[Table[Point[{i,j}],{i,3},{j,3}]]];Bob HanlonChantilly, VA USA ==== try:1 + x^2 /. {x -> 0}It will give you the 1 you wish.Matthias Bode.Gesendet: Montag, 22. Juli 2002 08:11An: mathgroup@smc.vnet.netBetreff: Q: Simplify with much less assumptionsI have one question regarding simplify answer with assumptions. Forexample, I have 1+x^2. The assumptions is x is much much less than 1.Therefore x^2 can be neglected under the above assumption. What I getafter simplification should be 1 only. Can anybody tell me how do thisin Mathematica? It seems there is no much less or much greaterHeather ==== Matthias.Bode@oppenheim.de schrieb:> try:> 1 + x^2 /. {x -> 0}> It will give you the 1 you wish.> Matthias Bode.> If you only want to neglect powers with exponent greater 1 you may usethe ruleIn[1]:=regel=x^(n_/;n>1)->0thenIn[2]:=1 + x + x^2 + x^3 + x^1.5 + x^(7/4) + x^0.5 + x^(3/4)/.regelOut[2]=1+x+x^0.5+x^(3/4)Gru¤ Peter-- =--=--=--=--=--=--=--=--=--=--=--=--=--= http://home.t-online.de/home/phbrf ==== > howdy,>> i have a Problem of the Form>> M . v == 0>> where M is a complex, numerical, 8x8 Matrix and v is an Vector with> eight unkown elements.>> M depends on one parameter x (real).>> There is no exact solution vor this equation. I will plot>> Abs[Det[M[x_]]]>> and watch for a local minimum. This way i can say: x must be something > like> ... or ... or. Now I need to get the vector v in this point x.>> Any hints for a nice function to complete this task?>>NullSpace will give you the v's. In fact, NullSpace works with symbolic expressions, so if the terms that make up M are not too complicated you can solve this problem entirely with NullSpace[M] and avoid the search for zeroes of the determinant entirely.SseziReply-To: jmt@dxdydz.net ==== Use Series and Normal :f[x] Series[1 + x^2, {x, 0, 1}]// Normalgivesf[0]+x f'[0]>> I have one question regarding simplify answer with assumptions. For> example, I have 1+x^2. The assumptions is x is much much less than 1.> Therefore x^2 can be neglected under the above assumption. What I get> after simplification should be 1 only. Can anybody tell me how do this> in Mathematica? It seems there is no much less or much greater>> Heather ==== Maybe the last example I gave is too simplified. In fact, the problem I always meet with is as follows:F(x,y,w,z) is a function of x,y,w and z where x,y,w and z are greater than zero. I want to simplify F(x,y,w,z) under the assumption that x is much less than y.----- Original Message ----- Sent: Monday, July 22, 2002 8:48 AM try: 1 + x^2 /. {x -> 0} It will give you the 1 you wish. Matthias Bode. Gesendet: Montag, 22. Juli 2002 08:11 An: mathgroup@smc.vnet.net Betreff: Q: Simplify with much less assumptions I have one question regarding simplify answer with assumptions. For example, I have 1+x^2. The assumptions is x is much much less than 1. Therefore x^2 can be neglected under the above assumption. What I get after simplification should be 1 only. Can anybody tell me how do this in Mathematica? It seems there is no much less or much greater Heather ==== I have one question regarding simplify answer with assumptions. For example, I have 1+x^2. The assumptions is x is much much less than 1. Therefore x^2 can be neglected under the above assumption. What I get after simplification should be 1 only. Can anybody tell me how do this in Mathematica? It seems there is no much less or much greater Heather ==== Dear Colleagues,I have a t-vectort = {0, 1, 1.5, 2, 2.5, 4, 6, 8, 10, 15, 20, 30};I want to subtract 0.15 from each element except the first to gettc15 = {0, 1 - 0.15, 1.50 - 0.15, 2 - 0.15, 2.5 - 0.15, 4 - 0.15, 6 -0.15, 8 - 0.15, 10 - 0.15, 15 - 0.15, 20 - 0.15, 30 - 0.15}; I then want to subtract 0.20 to gettc20 = {0, 1 - 0.20, 1.50 - 0.20, 2 - 0.20, 2.5 - 0.20, 4 - 0.20, 6 -0.20, 8 - 0.20, 10 - 0.20, 15 - 0.20, 20 - 0.20, 30 - 0.20}; Is there a way to automate this process for n subtractions from 0.15to 0.30 to yield individual t-vectors for tc15 through tc30 ?With Much Appreciation,Oscar ==== O.A. Linares, M.D., Ph.D. schrieb:> Dear Colleagues,> I have a t-vector> t = {0, 1, 1.5, 2, 2.5, 4, 6, 8, 10, 15, 20, 30};> I want to subtract 0.15 from each element except the first to get> tc15 = {0, 1 - 0.15, 1.50 - 0.15, 2 - 0.15, 2.5 - 0.15, 4 - 0.15, 6 -> 0.15, 8 - 0.15, 10 - 0.15, 15 - 0.15, 20 - 0.15, 30 - 0.15};> I then want to subtract 0.20 to get> tc20 = {0, 1 - 0.20, 1.50 - 0.20, 2 - 0.20, 2.5 - 0.20, 4 - 0.20, 6 -> 0.20, 8 - 0.20, 10 - 0.20, 15 - 0.20, 20 - 0.20, 30 - 0.20};> Is there a way to automate this process for n subtractions from 0.15> to 0.30 to yield individual t-vectors for tc15 through tc30 ?> With Much Appreciation,> Oscar> I don't know if this is the best way:tc15=Flatten[{First[t],Subtract[Rest[t],0.2]}]Gru¤ Peter-- =--=--=--=--=--=--=--=--=--=--=--=--=--= http://home.t-online.de/home/phbrf ==== Oscar,Some suggestions: t = {0, 1, 1.5, 2, 2.5, 4}; c = {a, b}; TC[t_, c_] := Module[{u}, u = Transpose[ReleaseHold[t + Hold[c]]]; u[[All,1]] = t[[1]]; u ]Test: TC[t, c] {{0, 1 + a, 1.5 + a, 2 + a, 2.5 + a, 4 + a}, {0, 1 + b, 1.5 + b, 2 + b, 2.5 + b, 4 + b}}To include assigning values to tca, tcb we may use TC1[t_, c_] := Module[{u}, Clear[`tc*]; u = Transpose[ReleaseHold[t + Hold[c]]]; u[[All,1]] = t[[1]]; Evaluate[ToExpression[(StringJoin[tc, ToString[#1]] & ) /@ c]]= u ]; (*the use of Evaluate is because in evaluating an expressionh[e,...]=rhs or h[e,...]:= expr the evaluation ofh[e,...] stops after evaluating the heads and the elements (ath*[e*,...]) --- otherwise we could not re-define. It could have been avoidedby introducing another symbol, v say, with v = ToExpression[ ...]; v=u*)Test: TC1[t, c] {{0, 1 + a, 1.5 + a, 2 + a, 2.5 + a, 4 + a}, {0, 1 + b, 1.5 + b, 2 + b, 2.5 + b, 4 + b}} tca {0, 1 + a, 1.5 + a, 2 + a, 2.5 + a, 4 + a}It may be more convenient to use indexed symbols: TC2[t_, c_] := Module[{u}, u = Transpose[ReleaseHold[t + Hold[c]]]; u[[All,1]] = t[[1]]; Evaluate[tc /@ c] = u ]; TC2[t, c] {{0, 1 + a, 1.5 + a, 2 + a, 2.5 + a, 4 + a}, {0, 1 + b, 1.5 + b, 2 + b, 2.5 + b, 4 + b}} tc[a] {0, 1 + a, 1.5 + a, 2 + a, 2.5 + a, 4 + a}--Allan---------------------Allan HayesMathematica Training and ConsultingLeicester UKwww.haystack.demon.co.ukhay@haystack.demon.co.ukVoice : +44 (0)116 271 4198> Dear Colleagues,>> I have a t-vector>> t = {0, 1, 1.5, 2, 2.5, 4, 6, 8, 10, 15, 20, 30};>> I want to subtract 0.15 from each element except the first to get>> tc15 = {0, 1 - 0.15, 1.50 - 0.15, 2 - 0.15, 2.5 - 0.15, 4 - 0.15, 6 -> 0.15, 8 - 0.15, 10 - 0.15, 15 - 0.15, 20 - 0.15, 30 - 0.15};>> I then want to subtract 0.20 to get>> tc20 = {0, 1 - 0.20, 1.50 - 0.20, 2 - 0.20, 2.5 - 0.20, 4 - 0.20, 6 -> 0.20, 8 - 0.20, 10 - 0.20, 15 - 0.20, 20 - 0.20, 30 - 0.20};>> Is there a way to automate this process for n subtractions from 0.15> to 0.30 to yield individual t-vectors for tc15 through tc30 ?>> With Much Appreciation,>> Oscar>Reply-To: ==== f5 (uncompiled) is about 2.5 times faster than f7 (compiled):Needs[Statistics`HypothesisTests`]f1[w_] := Count[Partition[w, 2, 1], {1, 0}]f2[w_] := Count[Drop[w, -1] - Drop[w, 1], 1] (* Allan Hayes *)f3[w_] := Count[Drop[w + 2RotateRight[w], 1], 2]f4[w_] := Tr[Drop[w, -1](Drop[w, -1] - Drop[w, 1])]f5[w_] := (Tr[w] - Tr[BitAnd[w, RotateLeft[w]]]) + If[w[[1]] == 0 && w[[-1]] == 1, -1, 0]f6[w_] := (Tr[#] - Tr[# Drop[w, 1]]) &[Drop[w, -1]](* Andrzej Kozlowski *)f7 = Compile[{{w, _Integer, 1}}, Count[Drop[w, -1] - Drop[w, 1], 1]];f8[w_List] /; Last[w] == 1 && First[w] == 0 := Count[w - RotateLeft[w],1];f8[w_List] := Count[Drop[w, -1] - Drop[w, 1], 1];trial[f_, g_] := (n = 2000000; w = Table[Random[Integer], {n}];First@Timing[#[w];]/Second & /@ {f, g} )test[f_, g_, n_Integer] := ( {t1, t2} = Transpose[trial[f, g] & /@ Range[n]]; Print[Mean /@ {t1, t2}]; Print[r = MeanTest[t1 - t2, 0, FullReport -> True]]; meanDiff = (FullReport /. r)[[1, 1, 1]]; Print[% difference = , meanDiff/Mean[t1]])test[f7, f5, 5]{0.12759999999999536, 0.07240000000000464}{FullReport -> TableForm[{{Mean, TestStat, Distribution}, {0.05519999999999072, 5.2573812925427745, StudentTDistribution[4]}}, TableHeadings -> {None, {Mean, TestStat, Distribution}}], OneSidedPValue -> 0.0031328222915485435}% difference = 0.4326018808Meanwhile, f5 is about 9 times faster than f8:test[f8, f5, 10]{0.5876000000000033, 0.06890000000000214}{FullReport -> TableForm[{{Mean, TestStat, Distribution}, {0.5187000000000012, 37.84563407920352, StudentTDistribution[9]}}, TableHeadings -> {None, {Mean, TestStat, Distribution}}], OneSidedPValue -> 1.558006714008781*^-11}% difference = 0.8827433628Bobby Treat-----Original Message-----(of course one can still make it faster by compiling:f = Compile[{{w, _Integer, 1}}, Count[Drop[w, -1] - Drop[w, 1], 1]]is about 6 times faster on my machine than the uncompiled version).Andrzej> Having quickly glanced through the avalanche of proposed solutions I > did not see following one.(if there was I apologize for claiming it as> my own):>> Count[w - RotateLeft[w], 1]>> According to my comparisons it is the fastest so far (the one that I > sent originally is one of the slowest)>> In[1]:=> w=Table[Random[Integer],{200000}];>> In[2]:=> Count[Partition[w,2,1],{1,0}]//Timing>> Out[2]=> {0.86 Second,50131}>> In[3]:=> Count[Drop[w,-1]-Drop[w,1],1]//Timing>> Out[3]=> {0.34 Second,50131}>> In[5]:=> Count[w-RotateLeft[w],1]//Timing>> Out[5]=> {0.29 Second,50131}>Andrzej KozlowskiToyama International UniversityJAPANhttp://platon.c.u-tokyo.ac.jp/andrzej/>> > [second posting in view of reported technical problem]>> Anthony,>> Take>> w = Table[Random[Integer], {200000}>> My first thought was, and several posts used this,>> Count[Partition[w, 2,1],{1,0}]//Timing>> {3.24 Second,49851}>> Later it occured to me to use arithmetic, which turned out to betwice >> as>> fast:>> Count[ Drop[w,-1] - Drop[w,1],1]//Timing>> {1.49 Second,49851}>> This is close to Selwyn Hollis's code>> Count[Drop[w+2RotateRight[w],1],2]//Timing>> {1.6 Second,49851}>> -->> 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>> Suppose w={1,1,1,0,0,1,0,1,0,0,1,0,0}.>> How can I count the number of occurrences of a 1 in w immediately> followed by a 0 in w?>> I have tried every incarnation of Count[] I can think of; forexample,>> Count[w,{___,1,0,___}]>> does not seem to work. In general, how can I count the number of> you!> --> Tony> _____________________> amendes@math.ucsd.edu> ==== In[1]:= Show[Table[Graphics[Point[{i, i}]], {i, 1, 9}]];Tomas GarzaMexico City----- Original Message ----- > P.S. In the end I will be doing three For loops in a nested formation> to generate the data to put on one graphic.> -Michael> ==== Michael,If you put the Show statement in the loop, then you are going to getmultiple plots. You want to first assemble the Points and then use one Showstatement.Also, it is much easier to use the Mathematica functional programming. Hereare two ways to obtain a list of Points.pts = Table[Point[{i, i}], {i, 9}]{Point[{1, 1}], Point[{2, 2}], Point[{3, 3}], Point[{4, 4}], Point[{5, 5}], Point[{6, 6}], Point[{7, 7}], Point[{8, 8}], Point[{9, 9}]}pts = Point[{#, #}] & /@ Range[9]{Point[{1, 1}], Point[{2, 2}], Point[{3, 3}], Point[{4, 4}], Point[{5, 5}], Point[{6, 6}], Point[{7, 7}], Point[{8, 8}], Point[{9, 9}]}Then use just one Show statement...Show[Graphics[{ AbsolutePointSize[3], pts}], Frame -> True];Or you could put the Table directly in the Show statement.Show[Graphics[{ AbsolutePointSize[3], Table[Point[{i, i}], {i, 9}]}], Frame -> True];David Parkdjmp@earthlink.nethttp://home.earthlink.net/~djmp/=== =This is a comment on, rather than a solution to, your problem. I had similar problems under OS9.1 whenever I was grading a series of student notebooks and pasting in comments from a fixed notebook of standard comments. The problem went away when I switched to OS X and Mathematica However there was a frustrating intermediate period where I upgraded to OS 9.2 to run Mathematica in the classic environment under OS X. Mathematica lost track of its password file (or whatever it uses) and asked for the number every time the front end started. The kernel would not start at all. Several hours on the phone to wri support did not help. Reinstalling under OS 9.2 did not help. Finally I hit upon reverting to OS 9.1, reinstalling, and the reverting to 9.2 (You can have as many different Mac operating systems on your disk as you like-contrary to popular belief). However, this fix would last only about a week and then I would have to redo it.In short, I had to upgrade both Mathematica and the OS to fix the problem.> mathgroup@smc.vnet.netGarry HelzerDepartment of MathematicsUniversity of MarylandCollege Park, MD 20742301-405-5176gah@math.umd.edu ==== Everyone, I've been trying to recast an iterative calculation I do as a procedural program in C as an elegant functional program in Mathematica 4.1. The Mathematica code is much more transparent, but the resultant execution time is more than two orders of magnitude longer. Any suggestions would be greatly appreciated.The following is a schematic of the problem.There are three equations in the iteration variable, n: G[n_] := ListIntegrate[xsec Phi[n]] Both xsec and Phi[n] are 400 points long. P[n_] := G[n]/(G[n]+(a constant)+D[n]) D[n] is a simple algebraic function of n. Phi[1] = Flux; Flux is 400 points long. Phi{n_] := Phi[n-1] Exp[-(1-P[n-1])*xsecThe goal is to evaluate P[n_] for an n around 1000. After running, I need to know all the values of P[n] and Phi[n] at each n from 1 to nmax. Note, P[n] is a number and Phi[n] is 400 points long.Currently,Timing[P[1]] = 0.1 sTiming[P[2]] = 0.2 sTiming[P[5]] = 8.4 s.I dont dare try to evaluate P[1000] as I need to do. Every time I evaluate these functions they recalculate from scratch. I think I need to somehow tell Mathematica to save the intermediate values. Curious is that the calculation time is going up like n^2, not like n as I would have thought. The equivalent procedural c-code runs in less than 1 second to evaluate P[1000].-Matt Rosen-- Matthew RosenHarvard-Smithsonian Center for AstrophysicsMail Stop 5960 Garden StreetCambridge, MA 02138e: mrosen@cfa.harvard.eduo: (617) 496-7614 ==== described in the Mathematica book section 2.4.9 (Dynamic programming) allows the entire code to run in about 10 seconds. I'm going to use a Do-loop construct to try and speed it up further.-Matt---Matthew RosenHarvard-Smithsonian Center for AstrophysicsMail Stop 5960 Garden StreetCambridge, MA 02138e: mrosen@cfa.harvard.eduo: (617) 496-7614 ==== Matthew,if want to retain your original formulation then change the assignment forPhi[n] toPhi[n_] := Phi[n] = Phi[n-1] Exp[-(1-P[n-1])*xsec]this uses a dynamic programming construct (look under dynamic programmingin HelpBrowser Master Index). You should also correct your error in thedefinition for G[n]. It should readG[n_]:=ListIntegrate[xsec Phi[n], h]where h is a step size.You should get even better performance if you use a vector-orientedapproach. Define the initial vectors and scalars and change their valuesinside a Do loop construct.Bye, Mariusz-- ==== =============================================== ===Mariusz JankowskiUniversity of Southern Mainemjkcc@usm.maine.edu> Everyone,> I've been trying to recast an iterative calculation I do as a> procedural program in C as an elegant functional program in> Mathematica 4.1. The Mathematica code is much more transparent, but> the resultant execution time is more than two orders of magnitude> longer. Any suggestions would be greatly appreciated.The following is> a schematic of the problem.> There are three equations in the iteration variable, n:>> G[n_] := ListIntegrate[xsec Phi[n]] Both xsec and Phi[n] are> 400 points long.>> P[n_] := G[n]/(G[n]+(a constant)+D[n]) D[n] is a simple algebraic> function of n.>> Phi[1] = Flux; Flux is 400 points long.> Phi{n_] := Phi[n-1] Exp[-(1-P[n-1])*xsec> The goal is to evaluate P[n_] for an n around 1000. After running, I> need to know all the values of P[n] and Phi[n] at each n from 1 to> nmax. Note, P[n] is a number and Phi[n] is 400 points long.>> Currently,>> Timing[P[1]] = 0.1 s> Timing[P[2]] = 0.2 s> Timing[P[5]] = 8.4 s.>> I dont dare try to evaluate P[1000] as I need to do. Every time I> evaluate these functions they recalculate from scratch. I think I> need to somehow tell Mathematica to save the intermediate values.> Curious is that the calculation time is going up like n^2, not like n> as I would have thought. The equivalent procedural c-code runs in> less than 1 second to evaluate P[1000].> -Matt Rosen> --> Matthew Rosen> Harvard-Smithsonian Center for Astrophysics> Mail Stop 59> 60 Garden Street> Cambridge, MA 02138>> e: mrosen@cfa.harvard.edu> o: (617) 496-7614>Reply-To: kuska@informatik.uni-leipzig.de ==== that is called dynamic programming and Phi[1] = Flux; Phi{n_] :=Phi[n]= Phi[n-1] Exp[-(1-P[n-1])*xsec G[n_] := G[n]=ListIntegrate[xsec Phi[n]] will save the function values for P[n] from previouscomputations. Jens> Everyone,> I've been trying to recast an iterative calculation I do as a> procedural program in C as an elegant functional program in> Mathematica 4.1. The Mathematica code is much more transparent, but> the resultant execution time is more than two orders of magnitude> longer. Any suggestions would be greatly appreciated.The following is> a schematic of the problem.> There are three equations in the iteration variable, n:> G[n_] := ListIntegrate[xsec Phi[n]] Both xsec and Phi[n] are> 400 points long.> P[n_] := G[n]/(G[n]+(a constant)+D[n]) D[n] is a simple algebraic> function of n.> > Phi[1] = Flux; Flux is 400 points long.> Phi{n_] := Phi[n-1] Exp[-(1-P[n-1])*xsec> The goal is to evaluate P[n_] for an n around 1000. After running, I> need to know all the values of P[n] and Phi[n] at each n from 1 to> nmax. Note, P[n] is a number and Phi[n] is 400 points long.> Currently,> Timing[P[1]] = 0.1 s> Timing[P[2]] = 0.2 s> Timing[P[5]] = 8.4 s.> I dont dare try to evaluate P[1000] as I need to do. Every time I> evaluate these functions they recalculate from scratch. I think I> need to somehow tell Mathematica to save the intermediate values.> Curious is that the calculation time is going up like n^2, not like n> as I would have thought. The equivalent procedural c-code runs in> less than 1 second to evaluate P[1000].> -Matt Rosen> --> Matthew Rosen> Harvard-Smithsonian Center for Astrophysics> Mail Stop 59> 60 Garden Street> Cambridge, MA 02138> e: mrosen@cfa.harvard.edu> o: (617) 496-7614 ==== Dear users of mathematical or statistical software,I would like to announce the foruth edition of my testreport Comparison of mathematical programs for data analysis which has just been finished. The testreport which is written in English is available as PDF file (Acrobat Reader) at the following website : http://www.scientificweb.com/ncrunch/index.htmlThis testreport contains information about the actual versions of the programs grouped by the following sections- Comparison of the mathematical functionality- Comparison of the graphical functionality- Functionality of the programming environment- Data import/export and data preprocessing functions- Available operating systems- Speed comparison- SummaryThe weighting for the above listed sections are all explained in the testreport so that an individual weighting could also be done.Sincerely,Stefan Steinhaus-- ==== ========================================================= ==== == Stefan Steinhaus Plievierpark 16 D-81737 M.9fnchen Germany Cell phone: ++49-(0)172-2976924 E-Mail: stefan@steinhaus-net.de ==== ================================= ==== ========================== Homepage : http://www.steinhaus-net.de Scientific Web : http://www.scientificweb.de http://www.scientificweb.com ==== ============================= ==== ==============================Reply-To: Peltio ==== Philippe Huber ha scritto>I have a dummy question: I would like to know if it is possible (and how)to>differentiate a symbolic sum like>>f(x1,...,xn)=Sum[x^2[[k]],{k,1,p}]>>with respect to xi. I should obtain 2xi.If you mean a term by term differentiation, you could try the Summa packageI uploaded on the mathsource a couple of years ago. It's a very thin andalmost trivial package but it can avoid you typing substitutions rules ateach passage.hope this can be of some help,Peltiopeltio at despammed dot comPSThe address inside the package is no longer valid.Sender: steve@smc.vnet.net ==== Many postings have appeared how to find the number of occurences (1,0) in asequence consisting of zeros and ones. My interest in these postings ismainly in the various techniques used to solve the problem rather than thespeed of the solution, though I immediately agree that a short and elegantsolution usually is fast as well.No doubt the shortest and most elegant solution is found by splitting thelist into pairs and simply count the number of lists {1,0}. But that turnsout not to be the fastest solution. The idea behind all other solutions isto look at the sequence of successive differences and then count the number1. So how to find this list of differences?Two ways have been demonstrated:Drop[lst, -1] - Drop[lst, 1]Drop[lst - RotateLeft[lst], 1]These two solutions are about as fast. Andrzej Kozlowsky noted that droppingthe last element in the second solution is only necessary when the list hasthe structure {0, ..., 1} which for long lists may give some gain of speed.There is a third way, as fast as the two others:ListCorrelate[{1,-1}, lst ]The list of differences consists of the elements 1, 0 and -1. Instead ofusing Count for counting the number of ones, Carl Woll in an ingenious wayreplaced the elements -1 by 0 and then used the trace function to count thenumber of ones. Successive improvements in the implementation of this ideabij Allan Hayes and Carl Woll lead to an amazing fast solution by AllanHayes.Still another approach is possible, based on the observation that betweenany two occurences of {1,0} in the list there must be an occurence of{0,1}. Therefore when the list starts with 1 and ends with 0, the number of1's in the list of diffences is one more than the number of -1's, etc. Usingthe same techniques as developed by Carl Woll and Allan Hayes we arrive atthe following solution:(Tr[BitXor[lst, RotateLeft[lst]]] + If[lst[[1]]==1,0,If[lst[[-1]]==1, -2,0]]) / 2Here is a timing for a list of length 5 10^6, compared with Alan's solution:In[126]:= lst = Table[Random[Integer], {5000000}];(Tr[lst]-Tr[BitAnd[lst,RotateLeft[lst]]])+ If[lst[[1]][Equal]0&&lst[[-1]][Equal]1,-1,0]//Timing(Tr[ BitXor[lst, RotateLeft[lst]]]+ If[lst[[1]][Equal]1, 0,If[lst[[-1]][Equal]1, -2,0]]) / 2 //TimingOut[127]={1.42 Second,1249704}Out[128]={0.88 Second,1249704}Fred SimonsEindhoven University of Technology ==== I am trying to generate a list of numbers where the number beingcalculated is dependant on the previous list member. What I (think I) need is a function, likeSeriesTable[expr,{InitialValue,imax}] where IntitialValue will be thefirst value in the list and expr will be evaluated on this value toform the second value and so on Imax times.My attempts to write such a function have failed miserably. Pleasehelp ... Barry ==== > I am trying to generate a list of numbers where the number being> calculated is dependant on the previous list member. > What I (think I) need is a function, like> SeriesTable[expr,{InitialValue,imax}] where IntitialValue will be the> first value in the list and expr will be evaluated on this value to> form the second value and so on Imax times.> My attempts to write such a function have failed miserably. Please> help ... BarryMaybe you can use NestList:Cell[TextData[ButtonBox[NestList, ButtonStyle->RefGuideLink]], Text]--Bhuvanesh,Wolfram Research. ==== I wish you could be more specific about the dependency between succesivemembers of the list. But, suppose there is a function, say f, such thatx(n), the n-th element, is equal to f[x(n-1)] for each n. Then, given x(1),the element x(n) is obtained with a function called Nest (see The Book orthe on-line Help). In other words, if the situation is such that (usingordinary notation) x(2) = f[x(1)]; x(3) = f[x(2)] = f[f[(x1)]]; ... x(n) =f[f[...f[x(1)]...] , then in Mathematica notation (assume x1 = x(1)):xn = Nest[f, x1, n]If you want to show all the elements, use NestList. If, on the other hand,the function depends on n, use Fold or FoldList (q.v.). These are extremelyimportant and powerful concepts which belong to the realm of functionalprogramming, and you'd be well advised to devote a few hours to becomefamiliar with them.Tomas GarzaMexico City----- Original Message ----->> My attempts to write such a function have failed miserably. Please> help ... Barry> ==== Barry,I think you are looking for the command NestList.A function ff is defined, for exampleff[a_]:=2aThe first element is definedIn[] fir=1Out[] 1Then ff is applied a number of times to the first and following elementsIn[] lst=NestList[ff,fir,10]Out[] {1,2,4,8,16,32,64,128,256,512,1024}Julio----- Original Message ----- > My attempts to write such a function have failed miserably. Please> help ... Barry> Reply-To: kuska@informatik.uni-leipzig.de ==== you need NestList[], here is a FactorialList[] with NestList[]FactorialList[n_Integer] := NestList[{#1[[1]] + 1, #[[2]]*(#1[[1]] + 1)} &, {1, 1}, n - 1] Jens> I am trying to generate a list of numbers where the number being> calculated is dependant on the previous list member.> What I (think I) need is a function, like> SeriesTable[expr,{InitialValue,imax}] where IntitialValue will be the> first value in the list and expr will be evaluated on this value to> form the second value and so on Imax times.> My attempts to write such a function have failed miserably. Please> help ... BarryReply-To: ==== Try something like this:t = {0, 1, 1.5, 2, 2.5, 4, 6, 8, 10, 15, 20, 30};Remove @@ Names[tc*](Evaluate@Symbol[tc <> ToString@#] = {0}~Join~(Rest[t] - #/100.)) & /@Range[15, 30, 5];?tc*Bobby Treat-----Original Message-----tc20 = {0, 1 - 0.20, 1.50 - 0.20, 2 - 0.20, 2.5 - 0.20, 4 - 0.20, 6 -0.20, 8 - 0.20, 10 - 0.20, 15 - 0.20, 20 - 0.20, 30 - 0.20}; Is there a way to automate this process for n subtractions from 0.15to 0.30 to yield individual t-vectors for tc15 through tc30 ?With Much Appreciation,Oscar ==== The following should do the trick :Needs[Statistics`ContinuousDistributions`];Needs[ Graphics`Graphics`];NormalDeviate[y_, mx_, vx_, n_] :=Module[{t}, t = Abs /@ RandomArray[NormalDistribution[mx, Sqrt[vx]], n];Table[Random[NormalDistribution[y, Sqrt[t[[i]]]]], {i, 1, n}]]Explation :1) Load the continuous Distrbutions and graphics modules2) Function NormalDeviate returns a list of n random numbers ~N(y,N(mx,vx) )>> I need to generate a Gaussian random variable y having mean =0 andvariance> =x.>> The variance x is itself a gaussian random variable having a known meanand> variance.> e.g. mean of x =5;> variance of x = 10;>> Can anyone suggest how to use this information to generate y ?>> thanks>> Salman>> ==== The following should do the trick :Needs[Statistics`ContinuousDistributions`];Needs[ Graphics`Graphics`];NormalDeviate[y_, mx_, vx_, n_] := Module[{t}, t = Abs /@ RandomArray[NormalDistribution[mx, Sqrt[vx]], n]; Table[Random[NormalDistribution[y, Sqrt[t[[i]]]]], {i, 1, n}]]Explation :1) Load the continuous Distrbutions and graphics modules2) Function NormalDeviate returns a list of n random numbers ~ N(y,N(mx,vx) )>> I need to generate a Gaussian random variable y having mean =0 andvariance> =x.>> The variance x is itself a gaussian random variable having a known meanand> variance.> e.g. mean of x =5;> variance of x = 10;>> Can anyone suggest how to use this information to generate y ?>> thanks>> Salman>> ==== >I have a t-vector>>t = {0, 1, 1.5, 2, 2.5, 4, 6, 8, 10, 15, 20, 30};>>I want to subtract 0.15 from each element except the first to get>>tc15 = {0, 1 - 0.15, 1.50 - 0.15, 2 - 0.15, 2.5 - 0.15, 4 - 0.15, 6 ->0.15, 8 - 0.15, 10 - 0.15, 15 - 0.15, 20 - 0.15, 30 - 0.15};>I then want to subtract 0.20 to get>>tc20 = {0, 1 - 0.20, 1.50 - 0.20, 2 - 0.20, 2.5 - 0.20, 4 - 0.20, 6 ->0.20, 8 - 0.20, 10 - 0.20, 15 - 0.20, 20 - 0.20, 30 - 0.20};>Is there a way to automate this process for n subtractions from 0.15>to 0.30 to yield individual t-vectors for tc15 through tc30 ?>Clear[t];t[x_] := Module[ {v={0,1,1.5,2,2.5,4,6,8,10,15,20,30}}, Join[{First[v]}, Rest[v]-(x/100.)]];Clear /@ Table[tc<>ToString[m], {m, 15, 30}];Evaluate[Table[ToExpression[tc<>ToString[m]], {m, 15, 30}]] = Table[t[15(1+m/15)], {m, 0, 15}];tc15==t[15]Truetc30==t[30]TrueBob HanlonChantilly, VA USA ==== Matthew,Check out Section 2.4.9 in The Mathematica Book - Functions That RememberValues They Have Found.I think that will prevent the recalculation.David Parkdjmp@earthlink.nethttp://home.earthlink.net/~djmp/--- --Original Message-----400 points long. P[n_] := G[n]/(G[n]+(a constant)+D[n]) D[n] is a simple algebraicfunction of n. Phi[1] = Flux; Flux is 400 points long. Phi{n_] := Phi[n-1] Exp[-(1-P[n-1])*xsecThe goal is to evaluate P[n_] for an n around 1000. After running, Ineed to know all the values of P[n] and Phi[n] at each n from 1 tonmax. Note, P[n] is a number and Phi[n] is 400 points long.Currently,Timing[P[1]] = 0.1 sTiming[P[2]] = 0.2 sTiming[P[5]] = 8.4 s.I dont dare try to evaluate P[1000] as I need to do. Every time Ievaluate these functions they recalculate from scratch. I think Ineed to somehow tell Mathematica to save the intermediate values.Curious is that the calculation time is going up like n^2, not like nas I would have thought. The equivalent procedural c-code runs inless than 1 second to evaluate P[1000].-Matt Rosen--Matthew RosenHarvard-Smithsonian Center for AstrophysicsMail Stop 5960 Garden StreetCambridge, MA 02138e: mrosen@cfa.harvard.eduo: (617) 496-7614 ==== Stef,If you want to install the DrawGraphics package from my web site, then theattached notebook shows a good method for making the plot and animation.GraphicsArray, or putting plots in two rectangles, is very difficult.Mathematica does not give easy or accurate control of the plot region andoverall aspect.Instead, I plot the two surfaces in one plot, giving the top surface anoffset. I also give the two surfaces different colors and use neutrallighting so they will show better.Anyone interested in the notebook with the example can contact me.David Parkdjmp@earthlink.nethttp://home.earthlink.net/~djmp/--- --Original Message----- Single output of both plots one after to the other just looks fine, but when they enter in an GraphicsArray[], the automatic scaling squeezes the lower cell width instead of stretching its height. >> demo start : just cut and paste into a new .nb >> !((( (* demo starts here *) )([IndentingNewLine])(()([IndentingNewLine]) (table1 ListPlot3D[ Table[Sin[x y], {x, 0, (3 Pi)/2, Pi/15}, {y, 0, (3 Pi)/2, Pi/15}], PlotRange -> {0, 0.25}, Axes -> {None, None, None}, ViewPoint -> {5, (-2.5), 0.6}, BoxRatios -> {10, 10, 1.25}];)([IndentingNewLine]) (table2 = ListPlot3D[ Table[Sin[x y], {x, 0, (3 Pi)/2, Pi/15}, {y, 0, (3 Pi)/2, Pi/15}], PlotRange -> {(-1), 0}, Axes -> {None, None, None}, ViewPoint -> {5, (-2.5), 1}, BoxRatios -> {10, 10, 5}];)([IndentingNewLine]) ()( [IndentingNewLine]) (table3 = {{table1}, {table2}};)([IndentingNewLine]) (Show[GraphicsArray[ table3, GraphicsSpacing -> 0]];)([IndentingNewLine]) ()([IndentingNewLine]) ( (* demo ends here*) )))) >> demo end >> Playing around with TableForm[] or RowsEqual-> or ImageSize-> didn't help so far. For all those of you that might have similar problems with plotting graphics: there are good support-procedures on the David-Park-homepage http://home.earthlink.net/~djmp/Mathematica.html But I couldn't find a solution for my problem. My general purpose is to generate an animated GIF, which shows a 360-degree-ßy-around a surface plot, that is cut into two parts at some z-value (this visualizes threshold effects on surfaces). Interested people can get a copy of my *.nb I carefully browsed through TMB and F1HELP for GraphicsArray-Options (well I think that F1 is pretty poor on these specific subjects), and of course also this newsgroup, but I couln't find the magic trick sought for. Bye Stef Mathematica-Compatible NotebookThis notebook can be used with any Mathematica-compatibleapplication, such as Mathematica, MathReader or Publicon. The datafor the notebook starts with the line containing stars above.To get the notebook into a Mathematica-compatible application, doone of the following:* Save the data starting with the line of stars above into a file with a name ending in .nb, then open the file inside the application;* Copy the data starting with the line of stars above to the clipboard, then use the Paste menu command inside the application.Data for notebooks contains only printable 7-bit ASCII and can beCR, LF or CRLF (Unix, Macintosh or MS-DOS style).NOTE: If you modify the data for this notebook not in a Mathematica-compatible application, you must delete the line below containingtry to use invalid cache data.For more information on notebooks and Mathematica-compatibleapplications, contact Wolfram Research: web: http://www.wolfram.com phone: +1-217-398-0700 (U.S.)Notebook reader applications are available free of charge fromWolfram Research.**************************************************** ***************)(*NotebookFileLineBreakTest NotebookFileLineBreakTest*)(*NotebookOptionsPosition[ 8180, 207]*)(*NotebookOutlinePosition[ 8823, 229]*)(* CellTagsIndexPosition[ 8779, 225]*)(*WindowFrame->Normal*)Notebook[{Cell[CellGroupData[{ Cell[Exploration (Skip), Section],Cell[BoxData[{ ( (* demo starts here *) [IndentingNewLine]), [IndentingNewLine], ((table1 ListPlot3D[ Table[Sin[x y], {x, 0, (3 Pi)/2, Pi/15}, {y, 0, (3 Pi)/2, Pi/15}], PlotRange -> {0, 0.25}, Axes -> {None, None, None}, ViewPoint -> {5, (-2.5), 0.6}, BoxRatios -> {10, 10, 1.25}];)), [IndentingNewLine], ((table2 = ListPlot3D[ Table[Sin[x y], {x, 0, (3 Pi)/2, Pi/15}, {y, 0, (3 Pi)/2, Pi/15}], PlotRange -> {(-1), 0}, Axes -> {None, None, None}, ViewPoint -> {5, (-2.5), 1}, BoxRatios -> {10, 10, 5}];)), [IndentingNewLine], (), [IndentingNewLine], ((table3 = {{table1}, {table2}};)), [IndentingNewLine], ((Show[ GraphicsArray[ table3, GraphicsSpacing -> .010]];)), [IndentingNewLine], (), [IndentingNewLine], ( (* demo ends here*) )}], Input],Cell[BoxData[ ((table1 ListPlot3D[ Table[Sin[x y], {x, 0, (3 Pi)/2, Pi/15}, {y, 0, (3 Pi)/2, Pi/15}], PlotRange -> {0, 0.25}, Axes -> {None, None, None}, ViewPoint -> {5, (-2.5), 0.6}, BoxRatios -> {10, 10, 1.25}, [IndentingNewLine]AspectRatio [Rule] 0.25];))], Input],Cell[BoxData[ ((table2 = ListPlot3D[ Table[Sin[x y], {x, 0, (3 Pi)/2, Pi/15}, {y, 0, (3 Pi)/2, Pi/15}], PlotRange -> {(-1), 0}, Axes -> {None, None, None}, ViewPoint -> {5, (-2.5), 1}, BoxRatios -> {10, 10, 5}];))], Input],Cell[BoxData[{ ((table3 = {{table1}, {table2}};)), [IndentingNewLine], ((Show[ GraphicsArray[table3, GraphicsSpacing -> 0]];))}], Input],Cell[CellGroupData[{Cell[BoxData[ (Show[ Graphics[[IndentingNewLine]{Rectangle[{1, 1}, {11, 5}, table1], [IndentingNewLine]Rectangle[{1, 6}, {11, 7}, table2]}], [IndentingNewLine]AspectRatio [Rule] Automatic, [IndentingNewLine]PlotRange [Rule] All, [IndentingNewLine]Frame [Rule] True, [IndentingNewLine]ImageSize [Rule] 400])], Input],Cell[BoxData[ TagBox[([SkeletonIndicator] Graphics [SkeletonIndicator]), False, Editable->False]], Output]}, Open ]]}, Closed]],Cell[CellGroupData[{Cell[Using DrawGraphics, Section],Cell[You need this package from my web site., Text],Cell[BoxData[ (Needs[])], Input],Cell[, Text],Cell[BoxData[ ((f[x_, y_] := Sin[x y];))], Input],Cell[TextData[{ Trying to use a graphic array, or to place the plots in two rectangles, is very difficult because , StyleBox[Mathematica, FontSlant->Italic], does not give us sure or easy control of the aspect ratio and plot region. Instead, I plot two surfaces with a min value, split value and max value. I parametrize the top and bottom surfaces and use a parametric plot. I give each surface a different color. I also give the polygon edges a subdued color which is part way between the surface color and black. I give the top surface an offset. NeutralLighting is a DrawGraphics routine that inserts Lighting options. It controls the saturation, brightness and ambient lighting, and you can also rotate the lights if you wish. The surface colors show much better if the lighting has low color saturation.}], Text],Cell[This makes the basic plot., Text],Cell[BoxData[ ((plot1 = [IndentingNewLine]Module[[IndentingNewLine]{min (-1), [IndentingNewLine]zsplit = 0, [IndentingNewLine]max 0.25, [IndentingNewLine]offset 0.25, [IndentingNewLine]bottom, top, x, y}, [IndentingNewLine]bottom = {x, y, Max[min, Min[zsplit, f[x, y]]]}; [IndentingNewLine]top = {x, y, Max[zsplit, Min[max, f[x, y]]] + offset}; [IndentingNewLine][IndentingNewLine]Draw3DItems[[ IndentingNewLine]{SurfaceColor[SkyBlue], EdgeForm[(ColorMix[SkyBlue, Black])[ 0.5]], [IndentingNewLine]ParametricDraw3D[ top // Evaluate, {x, 0, (3 Pi)/2}, {y, 0, (3 Pi)/2}, PlotPoints [Rule] 50], [IndentingNewLine]SurfaceColor[ Salmon], EdgeForm[(ColorMix[Salmon, Black])[ 0.5]], [IndentingNewLine]ParametricDraw3D[ bottom // Evaluate, {x, 0, (3 Pi)/2}, {y, 0, (3 Pi)/2}, PlotPoints [Rule] 50]}, [IndentingNewLine]ViewPoint -> {1.783, (-2.851), 0.379}, [IndentingNewLine]NeutralLighting[0.3, 0.5, 0.1], [IndentingNewLine]Boxed [Rule] False, [IndentingNewLine]SphericalRegion [Rule] True, [IndentingNewLine]ImageSize [Rule] 500[IndentingNewLine]][IndentingNewLine]];))], Input],Cell[, Text],Cell[BoxData[{ (SpinShow[plot1, SpinOrigin [Rule] {0, 0, 0.5}, SpinDistance [Rule] 10]), [IndentingNewLine], (SelectionMove[EvaluationNotebook[], All, GeneratedCell]), n, (FrontEndTokenExecute[]), n, (FrontEndTokenExecute[])}], Input],Cell[, Text]}, Open ]]},ScreenRectangle->{{0, 1280}, {0, 943}},WindowSize->{625, 729},WindowMargins->{{0, Automatic}, {Automatic, 0}}](******************************************************** ***********the top of the file. The cache data will then be recreated whenyou save this file from within Mathematica.************************************************* ******************)(*CellTagsOutlineCellTagsIndex->{}*)(* CellTagsIndexCellTagsIndex->{}*)(*NotebookFileOutline Notebook[{Cell[CellGroupData[{Cell[1727, 52, 37, 0, 59, Section],Cell[1767, 54, 1360, 27, 400, Input],Cell[3130, 83, 418, 9, 104, Input],Cell[3551, 94, 342, 7, 84, Input],Cell[3896, 103, 174, 3, 50, Input],Cell[CellGroupData[{Cell[4095, 110, 396, 7, 150, Input],Cell[4494, 119, 130, 3, 29, Output]}, Open ]]}, Closed]],Cell[CellGroupData[{Cell[4673, 128, 37, 0, 39, Section],Cell[4713, 130, 55, 0, 33, Text],Cell[4771, 132, 73, 1, 30, Input],Cell[4847, 135, 133, 3, 33, Text],Cell[4983, 140, 60, 1, 30, Input],Cell[5046, 143, 859, 14, 147, Text],Cell[5908, 159, 42, 0, 33, Text],Cell[5953, 161, 1483, 25, 525, Input],Cell[7439, 188, 146, 3, 52, Text],Cell[7588, 193, 323, 5, 90, Input],Cell[7914, 200, 250, 4, 52, Text]}, Open ]]}]*)(****************************************************** *************End of Mathematica Notebook file.********************************************************* **********) ==== Oscar,t = {0, 1, 1.5, 2, 2.5, 4, 6, 8, 10, 15, 20, 30};u[sub_] := Join[{First[t]}, Rest[t] - sub]u[0.15]{0, 0.85, 1.35, 1.85, 2.35, 3.85, 5.85, 7.85, 9.85, 14.85, 19.85, 29.85}Table[u[sub], {sub, 0.15, 0.30, 0.05}]{{0, 0.85, 1.35, 1.85, 2.35, 3.85, 5.85, 7.85, 9.85, 14.85, 19.85, 29.85},{0, 0.8, 1.3, 1.8, 2.3, 3.8, 5.8, 7.8, 9.8, 14.8, 19.8, 29.8}, {0, 0.75, 1.25, 1.75, 2.25, 3.75, 5.75, 7.75, 9.75, 14.75, 19.75, 29.75}, {0, 0.7, 1.2, 1.7, 2.2, 3.7, 5.7, 7.7, 9.7, 14.7, 19.7, 29.7}}David Parkdjmp@earthlink.nethttp://home.earthlink.net/~djmp/Is there a way to automate this process for n subtractions from 0.15to 0.30 to yield individual t-vectors for tc15 through tc30 ?With Much Appreciation,OscarReply-To: ==== For instance,ClearAll[G]G[n_] := G[n] = xsec ListIntegrate[Phi[n]]causes the G values to be saved as they're calculated. (Taking xsecoutside ListIntegrate should be equivalent, right?) Calculating G[1000]right away will cause iteration limits to be exceeded, so you need tocalculate from the bottom up:G /@ Range[1000];Use the same trick to save values of Phi and P, of course. Then thebottom-up calculation of G will cause all the other calculations to bestored.I am sure the C code was somehow storing values, too.Bobby-----Original Message----- G[n_] := ListIntegrate[xsec Phi[n]] Both xsec and Phi[n] are 400 points long. P[n_] := G[n]/(G[n]+(a constant)+D[n]) D[n] is a simple algebraic function of n. Phi[1] = Flux; Flux is 400 points long. Phi{n_] := Phi[n-1] Exp[-(1-P[n-1])*xsecThe goal is to evaluate P[n_] for an n around 1000. After running, I need to know all the values of P[n] and Phi[n] at each n from 1 to nmax. Note, P[n] is a number and Phi[n] is 400 points long.Currently,Timing[P[1]] = 0.1 sTiming[P[2]] = 0.2 sTiming[P[5]] = 8.4 s.I dont dare try to evaluate P[1000] as I need to do. Every time I evaluate these functions they recalculate from scratch. I think I need to somehow tell Mathematica to save the intermediate values. Curious is that the calculation time is going up like n^2, not like n as I would have thought. The equivalent procedural c-code runs in less than 1 second to evaluate P[1000].-Matt Rosen-- Matthew RosenHarvard-Smithsonian Center for AstrophysicsMail Stop 5960 Garden StreetCambridge, MA 02138e: mrosen@cfa.harvard.eduo: (617) 496-7614 ==== > Everyone,> I've been trying to recast an iterative calculation I do as a> procedural program in C as an elegant functional program in> Mathematica 4.1. The Mathematica code is much more transparent, but> the resultant execution time is more than two orders of magnitude> longer. Any suggestions would be greatly appreciated.The following is> a schematic of the problem.> There are three equations in the iteration variable, n:>> G[n_] := ListIntegrate[xsec Phi[n]] Both xsec and Phi[n] are> 400 points long.>> P[n_] := G[n]/(G[n]+(a constant)+D[n]) D[n] is a simple algebraic> function of n.>> Phi[1] = Flux; Flux is 400 points long.> Phi{n_] := Phi[n-1] Exp[-(1-P[n-1])*xsec> The goal is to evaluate P[n_] for an n around 1000. After running, I> need to know all the values of P[n] and Phi[n] at each n from 1 to> nmax. Note, P[n] is a number and Phi[n] is 400 points long.>> Currently,>> Timing[P[1]] = 0.1 s> Timing[P[2]] = 0.2 s> Timing[P[5]] = 8.4 s.>> I dont dare try to evaluate P[1000] as I need to do. Every time I> evaluate these functions they recalculate from scratch. I think I> need to somehow tell Mathematica to save the intermediate values.> Curious is that the calculation time is going up like n^2, not like n> as I would have thought. The equivalent procedural c-code runs in> less than 1 second to evaluate P[1000].>You may want to cache your values, especially since none of the lists are very long. Try defining P as P[n_]:=P[n]=G[n]/(G[n]+...) and Phi[n_] as Phi[n_]:=Phi[n]=Phi[n-1] Exp[-(1-P[n-1])*xsec]. For that matter you may want to do the same thing with G. Doing this for a simplified version of your system (constant = 1, D[n_]:=n^2 etc.) I get the following timings(Dialog) In[153]:=Timing[P[1];]Timing[P[2];]Timing[P[5];](Dialog) Out[153]={0.02 Second,Null}(Dialog) Out[154]={0.03 Second,Null}(Dialog) Out[155]={0.07 Second,Null}Ssezi ==== there is a way to automate this process.Try:Table[{tc15[[1]], Take[tc15, -(Length[tc15] - 1)] - n}, {n, 0.15, 0.3, 0.05}] // Flatten;Partition[%, Length[tc15]]Matthias Bode.Gesendet: Dienstag, 23. Juli 2002 07:52An: mathgroup@smc.vnet.netBetreff: elementwise vector scalar subtractionDear Colleagues,I have a t-vectort = {0, 1, 1.5, 2, 2.5, 4, 6, 8, 10, 15, 20, 30};I want to subtract 0.15 from each element except the first to gettc15 = {0, 1 - 0.15, 1.50 - 0.15, 2 - 0.15, 2.5 - 0.15, 4 - 0.15, 6 -0.15, 8 - 0.15, 10 - 0.15, 15 - 0.15, 20 - 0.15, 30 - 0.15}; I then want to subtract 0.20 to gettc20 = {0, 1 - 0.20, 1.50 - 0.20, 2 - 0.20, 2.5 - 0.20, 4 - 0.20, 6 -0.20, 8 - 0.20, 10 - 0.20, 15 - 0.20, 20 - 0.20, 30 - 0.20}; Is there a way to automate this process for n subtractions from 0.15to 0.30 to yield individual t-vectors for tc15 through tc30 ?With Much Appreciation,Oscar ==== I need to create the following list:{{equation1, equation2,...equation_n},{x1,x1_0},{x2,x2_0},...{xn,xn_0}}In [48]:= Append[{{equation1, equation2}}, List[{x1, x1_0}, {x2, x2_0}]]Out[48]= {{equation1, equation2}, {{x1, 0}, {x2, 0}}}doesn't give the desired result which isOut[]= {{equation1, equation2}, {x1, x1_0}, {x2, x2_0}}without the brackets.Has somebody an elegant solution for this problem?!e. ==== Erwin, Flatten[{{{equation1,equation2}},List[{x1,x1_0},{x2,x2_0}]},1 ] {{equation1,equation2},{x1,0},{x2,0}}--Allan--------------- ------Allan HayesMathematica Training and ConsultingLeicester UKwww.haystack.demon.co.ukhay@haystack.demon.co.ukVoice : +44 (0)116 271 4198>> I need to create the following list:>> {{equation1, equation2,...equation_n},{x1,x1_0},{x2,x2_0},...{xn,xn_0}}> In[48]:= Append[{{equation1, equation2}}, List[{x1, x1_0}, {x2, x2_0}]]> Out[48]= {{equation1, equation2}, {{x1, 0}, {x2, 0}}}>> doesn't give the desired result which is>> Out[]= {{equation1, equation2}, {x1, x1_0}, {x2, x2_0}}> without the brackets.>> Has somebody an elegant solution for this problem?> !e.>> ==== I guess you could improve your notation a little to make things clearer, butin any case (and of course it would be helpful to know how you have yourequations and variables stored or how they are obtained presumably one afterthe other), you may try:In[1]:={{equation1, equation2}, Sequence @@ {{x1, x10}, {x2, x20}}}Out[1]={{equation1, equation2}, {x1, x10}, {x2, x20}}Tomas GarzaMexico City----- Original Message -----> Out[48]= {{equation1, equation2}, {{x1, 0}, {x2, 0}}}>> doesn't give the desired result which is>> Out[]= {{equation1, equation2}, {x1, x1_0}, {x2, x2_0}}> without the brackets.>> Has somebody an elegant solution for this problem?> !e.>>Reply-To: kuska@informatik.uni-leipzig.de ==== Join[] ?Join[{{equation1, equation2}}, List[{x1, x10}, {x2, x20}]] Jens> I need to create the following list:> {{equation1, equation2,...equation_n},{x1,x1_0},{x2,x2_0},...{xn,xn_0}}> In[48]:= Append[{{equation1, equation2}}, List[{x1, x1_0}, {x2, x2_0}]]> Out[48]= {{equation1, equation2}, {{x1, 0}, {x2, 0}}}> doesn't give the desired result which is> Out[]= {{equation1, equation2}, {x1, x1_0}, {x2, x2_0}}> without the brackets.> Has somebody an elegant solution for this problem?> !e. ==== Construct a matrix which has symbol a in the upper left (1,1) element and symbols I c in the rest of the top row and the left-most column, dot it into itself three times, and display the result using MatrixForm.The top row in the display now has I c (a^2 - 4c^2) ; the left-most column now has I a^2 c - 4 I c^3 . Not exactly a serious problem, but not exactly clean either. Makes it harder to see at a glance whether a given matrix is symmetric above the diagonal (could be a problem in a more complicated situation). Could possibly mess up the behavior of pattern matching rules?????? ==== In[1]:=t = {0, 1, 1.5, 2, 2.5, 4, 6, 8, 10, 15, 20, 30}; In[2]:=tc = Table[Prepend[Rest[t] - j, First[t]], {j, 0.15, 0.3, 0.05}]; Tomas GarzaMexico City----- Original Message ----- > tc15 = {0, 1 - 0.15, 1.50 - 0.15, 2 - 0.15, 2.5 - 0.15, 4 - 0.15, 6 -> 0.15, 8 - 0.15, 10 - 0.15, 15 - 0.15, 20 - 0.15, 30 - 0.15};> I then want to subtract 0.20 to get> tc20 = {0, 1 - 0.20, 1.50 - 0.20, 2 - 0.20, 2.5 - 0.20, 4 - 0.20, 6 -> 0.20, 8 - 0.20, 10 - 0.20, 15 - 0.20, 20 - 0.20, 30 - 0.20};> Is there a way to automate this process for n subtractions from 0.15> to 0.30 to yield individual t-vectors for tc15 through tc30 ?> With Much Appreciation,> Oscar> ==== > Dear Colleagues,>> I have a t-vector>> t = {0, 1, 1.5, 2, 2.5, 4, 6, 8, 10, 15, 20, 30};>> I want to subtract 0.15 from each element except the first to get>> tc15 = {0, 1 - 0.15, 1.50 - 0.15, 2 - 0.15, 2.5 - 0.15, 4 - 0.15, 6 -> 0.15, 8 - 0.15, 10 - 0.15, 15 - 0.15, 20 - 0.15, 30 - 0.15};>> I then want to subtract 0.20 to get>> tc20 = {0, 1 - 0.20, 1.50 - 0.20, 2 - 0.20, 2.5 - 0.20, 4 - 0.20, 6 -> 0.20, 8 - 0.20, 10 - 0.20, 15 - 0.20, 20 - 0.20, 30 - 0.20};>> Is there a way to automate this process for n subtractions from 0.15> to 0.30 to yield individual t-vectors for tc15 through tc30 ?>>The only difficulty seems to be retaining the zero at the beginning of the list, so we could just define a pure function to stick it on. The rest can be handled with a simple table so the expression:Block[{temp=Rest[t]},{0,##}&@@@Table[temp-(0.15-i 0.5),{i,0,3}]]should do the trick.SseziReply-To: ==== When you say, x is much less than y, do you mean close to 0? Or closeto -Infinity? In either case, there's no good definition of simplifyunless you mean to take the Limit, and that only works if the functionhas a limit at 0 or -Infinity. You can use Limit or you can simplysubstitute x->0.Be clear on what you want, and I think the solution will become obvious.Bobby-----Original Message---------- Original Message ----- Sent: Monday, July 22, 2002 8:48 AMassumptions try: 1 + x^2 /. {x -> 0} It will give you the 1 you wish. Matthias Bode. Gesendet: Montag, 22. Juli 2002 08:11 An: mathgroup@smc.vnet.net Betreff: Q: Simplify with much less assumptions I have one question regarding simplify answer with assumptions. For example, I have 1+x^2. The assumptions is x is much much less than 1. Therefore x^2 can be neglected under the above assumption. What I get after simplification should be 1 only. Can anybody tell me how do this in Mathematica? It seems there is no much less or much greater Heather ==== Oscar,Here's my solution.In[1]:= t = {0, 1, 1.5, 2, 2.5, 4, 6, 8, 10, 15, 20, 30}Out[1]= {0,1,1.5,2,2.5,4,6,8,10,15,20,30}Define the first, last, and increment of the numbers to be substracted.In[2]:= first=.15 last=.3 increm=.05Out[2]= 0.15Out[3]= 0.3Out[4]= 0.05Define a list of elements to be substracted, for each value.In[5]:= =tc=Table[Table[first-increm+increm*i,{Length[t]-1}],{i,( last-first)/increm+1}]/.{a_/;NumberQ[a],b__}=AE{0,a,b}Out[5] = {{0,0.15,0.15,0.15,0.15,0.15,0.15,0.15,0.15,0.15,0.15,0.15},{ 0,0.2,0.2,0.2,0.2,0.2,0.2,0.2,0.2,0.2,0.2,0.2},{ 0,0.25,0.25,0.25,0.25,0.25,0.25,0.25,0.25,0.25,0.25,0.25},{ 0,0.3,0.3,0.3,0.3,0.3,0.3,0.3,0.3,0.3,0.3,0.3}}Substracting each tc[[i]] from t, we get each of the lists tc you were looking for.tt[[1]] is your tc15, and so on.In[6]:= tt=Table[Table[t[[i]]-tc[[j,i]],{i,Length[t]}],{j,Length[tc] }]Out[6]= {{0,0.85,1.35,1.85,2.35,3.85,5.85,7.85,9.85,14.85,19.85,29.85 },{0,0.8,1.3,1.8,2.3,3.8,5.8,7.8,9.8,14.8,19.8,29.8},{ 0,0.75,1.25,1.75,2.25,3.75,5.75,7.75,9.75,14.75,19.75,29.75}, {0,0.7,1.2,1.7,2.2,3.7,5.7,7.7,9.7,14.7,19.7,29.7}}Julio --------------------------------Dear Colleagues,I have a t-vectort = {0, 1, 1.5, 2, 2.5, 4, 6, 8, 10, 15, 20, 30};I want to subtract 0.15 from each element except the first to gettc15 = {0, 1 - 0.15, 1.50 - 0.15, 2 - 0.15, 2.5 - 0.15, 4 - 0.15, 6 -0.15, 8 - 0.15, 10 - 0.15, 15 - 0.15, 20 - 0.15, 30 - 0.15};I then want to subtract 0.20 to gettc20 = {0, 1 - 0.20, 1.50 - 0.20, 2 - 0.20, 2.5 - 0.20, 4 - 0.20, 6 -0.20, 8 - 0.20, 10 - 0.20, 15 - 0.20, 20 - 0.20, 30 - 0.20};Is there a way to automate this process for n subtractions from 0.15to 0.30 to yield individual t-vectors for tc15 through tc30 ?With Much Appreciation,Oscar ==== I have a question regarding substitute of an expression with indexvariables..I need to make a table for some products of irreduciblepolynomials (Irreducible factors of x^63 -1) . But they are so large and Ican't fit them into the columns of my table. So I need to use thesesubstitutions{S_1, S_2, S_3, S_4, S_5, S_6, S_7, S_8, S_9, S_10, S_11, S_12, S_13, S_14}: ------> {1 + x, 1 + x + x^2, 1 + x + x^3, 1 + x^2 + x^3, 1 + x + x^6, 1 + x^3 + x^6, 1 + x + x^2 + x^4 + x^6, 1 + x + x^3 + x^4 + x^6, 1 +x^5 + x^6, 1 + x + x^2 + x^5 + x^6, 1 + x^2 + x^3 + x^5 + x^6, 1 + x + x^4+ x^5 + x^6, 1 + x^2 + x^4 + x^5 + x^6}***** The right side is a list of irreducible polynomials which is assignedto {S_1, S_2,.... S_14}.*******For example instead of putting this large expression (1 + x) (1 + x + x^2)(1 + x + x^3) (1 + x + x^6) (1 + x^3 + x^6) (1 + x + x^2 + x^4 + x^6) (1 +x + x^3 + x^4 + x^6) (1 + x + x^2 + x^5 + x^6) in my table I can write it intems of S_i's in this form S_1 S_2 S_3 S_4 S_5 S_6 S_7 S_8.I tried ReplaceAll but it changes i.e. the above example to S_1 (S_1+x^3)(S_1+x_6) .... Which is not what I want.Can anybody tell me how to do this.CHEKAD ==== Previous responses have observed that getting the order of the rules correctis the key to a solution.This is clearly the right way for this problem. However I wondered what onemight do in general.Here is a slower solution that uses Replace. fcts=(1+x) (1+x+x^2)(1+x+x^3)(1+x+x^6)*(1+x^3+x^6)*(1+x+x^2+x^4+x^6)*(1+ x+ x^3+x^4+x^6)*(1+x+x^2+x^5+x^6);rls=Thread[{1+x,1+x+x^2,1+x+x ^3,1+x^2+x^3,1+x+x^6,1+x^3+x^6,1+x+x^2+x^4+x^6, 1+x+x^3+x^4+x^6,1+x^5+x^6,1+x+x^2+x^5+x^6,1+x^2+x^3+x^5+x^6, 1+x+x^4+x^5+x^6,1+x^2+x^4+x^5+x^6}[Rule]{S01,S02,S03,S04, S05,S06, S07,S08,S09,S10,S11,S12,S13}];Provided that there are two or more factors: rp1[p_,rls_]:=Replace[ p,rls,{1}] rp1[fcts, rls] S01 S02 S03 S05 S06 S07 S08 S10If there may be only one factor: rp2[p_,rls_]:=Module[{a},{Replace[a p,rls,{1}],a=1}[[1]]] rp2[fcts, rls] S01 S02 S03 S05 S06 S07 S08 S10--Allan---------------------Allan HayesMathematica Training and ConsultingLeicester UKwww.haystack.demon.co.ukhay@haystack.demon.co.ukVoice : +44 (0)116 271 4198> I have a question regarding substitute of an expression with index> variables..I need to make a table for some products of irreducible> polynomials (Irreducible factors of x^63 -1) . But they are so large and I> can't fit them into the columns of my table. So I need to use these> substitutions>> {S_1, S_2, S_3, S_4, S_5, S_6, S_7, S_8, S_9, S_10, S_11, S_12, S_13,S_14}> : ------> {1 + x, 1 + x + x^2, 1 + x + x^3, 1 + x^2 + x^3, 1 + x + x^6,> 1 + x^3 + x^6, 1 + x + x^2 + x^4 + x^6, 1 + x + x^3 + x^4 + x^6, 1 +> x^5 + x^6, 1 + x + x^2 + x^5 + x^6, 1 + x^2 + x^3 + x^5 + x^6, 1 + x +x^4> + x^5 + x^6, 1 + x^2 + x^4 + x^5 + x^6}>> ***** The right side is a list of irreducible polynomials which isassigned> to {S_1, S_2,.... S_14}.*******>> For example instead of putting this large expression (1 + x) (1 + x +x^2)> (1 + x + x^3) (1 + x + x^6) (1 + x^3 + x^6) (1 + x + x^2 + x^4 + x^6) (1+> x + x^3 + x^4 + x^6) (1 + x + x^2 + x^5 + x^6) in my table I can write itin> tems of S_i's in this form S_1 S_2 S_3 S_4 S_5 S_6 S_7 S_8.>> I tried ReplaceAll but it changes i.e. the above example to S_1(S_1+x^3)> (S_1+x_6) .... Which is not what I want.>> Can anybody tell me how to do this.> CHEKAD>> ==== Chekad,I donÇt know if I understood your problem correctly.If you just want to name each polinomial i as S_i, you could name thealready entered list as s, and each element s[[i]] will be each polinomial.In[] s={1 + x, 1 + x + x^2, 1 + x + x^3, 1 + x^2 + x^3, 1 + x + x^6, 1 + x^3 + x^6, 1 + x + x^2 + x^4 + x^6, 1 + x + x^3 + x^4 + x^6, 1 +x^5 + x^6, 1 + x + x^2 + x^5 + x^6, 1 + x^2 + x^3 + x^5 + x^6, 1 + x + x^4+ x^5 + x^6, 1 + x^2 + x^4 + x^5 + x^6}Out[] {1 + x, 1 + x + x^2, 1 + x + x^3, 1 + x^2 + x^3, 1 + x + x^6, 1 + x^3 + x^6, 1 + x + x^2 + x^4 + x^6, 1 + x + x^3 + x^4 + x^6, 1 +x^5 + x^6, 1 + x + x^2 + x^5 + x^6, 1 + x^2 + x^3 + x^5 + x^6, 1 + x + x^4+ x^5 + x^6, 1 + x^2 + x^4 + x^5 + x^6}In[] s[[1]]Out[] 1+xIn[] s[[13]]Out 1 + x^2 + x^4 + x^5 + x^6I you want to get the product of all the elements of the list, you can applythe command Times to the list sApply[Times,s]or itÇs equivalent Times@@sHope this helps,Julio----- Original Message ----->> {S_1, S_2, S_3, S_4, S_5, S_6, S_7, S_8, S_9, S_10, S_11, S_12, S_13,S_14}> : ------> {1 + x, 1 + x + x^2, 1 + x + x^3, 1 + x^2 + x^3, 1 + x + x^6,> 1 + x^3 + x^6, 1 + x + x^2 + x^4 + x^6, 1 + x + x^3 + x^4 + x^6, 1 +> x^5 + x^6, 1 + x + x^2 + x^5 + x^6, 1 + x^2 + x^3 + x^5 + x^6, 1 + x +x^4> + x^5 + x^6, 1 + x^2 + x^4 + x^5 + x^6}>> ***** The right side is a list of irreducible polynomials which isassigned> to {S_1, S_2,.... S_14}.*******>> For example instead of putting this large expression (1 + x) (1 + x +x^2)> (1 + x + x^3) (1 + x + x^6) (1 + x^3 + x^6) (1 + x + x^2 + x^4 + x^6) (1+> x + x^3 + x^4 + x^6) (1 + x + x^2 + x^5 + x^6) in my table I can write itin> tems of S_i's in this form S_1 S_2 S_3 S_4 S_5 S_6 S_7 S_8.>> I tried ReplaceAll but it changes i.e. the above example to S_1(S_1+x^3)> (S_1+x_6) .... Which is not what I want.>> Can anybody tell me how to do this.> CHEKAD>> ==== To start with, you have only 13 *and not 14* polynomials. I would suggestyou make a straightforward assignment, such asIn[1]:=Clear[s];s = {1 + x, 1 + x + x^2, 1 + x + x^3, 1 + x^2 + x^3, 1 + x + x^6, 1 + x^3 + x^6, 1 + x + x^2 + x^4 + x^6, 1 + x + x^3 + x^4 + x^6, 1 + x^5 + x^6, 1 + x + x^2 + x^5 + x^6, 1 + x^2 + x^3 + x^5 + x^6, 1 + x + x^4 + x^5 + x^6, 1 + x^2 + x^4 + x^5 + x^6};Here you check that there are only 13:In[2]:=Length[s]Out[2]=13so that, for example,In[3]:=s[[1]]Out[3]=1 + xThen, you getIn[4]:=Product[s[[i]], {i, 1, 8}]Out[4]=(1 + x)*(1 + x + x^2)*(1 + x + x^3)*(1 + x^2 + x^3)* (1 + x + x^6)*(1 + x^3 + x^6)*(1 + x + x^2 + x^4 + x^6)* (1 + x + x^3 + x^4 + x^6)as desired. You could benefit enormously by using a proper notation anddisplay form. DefineIn[5]:=Subscript[s_, n_] := s[[n]]and display this cell (and other cells, too) as standard form (select thecell or cells, and then Cell | Convert To | Standard Form). You'll see yourformulas displayed very nicely. It is easy to write Subscript[s, n] bytyping s, then Ctrl - (i.e., Ctrl key and then minus sign) and then n.Tomas GarzaMexico City----- Original Message ----->> {S_1, S_2, S_3, S_4, S_5, S_6, S_7, S_8, S_9, S_10, S_11, S_12, S_13,S_14}> : ------> {1 + x, 1 + x + x^2, 1 + x + x^3, 1 + x^2 + x^3, 1 + x + x^6,> 1 + x^3 + x^6, 1 + x + x^2 + x^4 + x^6, 1 + x + x^3 + x^4 + x^6, 1 +> x^5 + x^6, 1 + x + x^2 + x^5 + x^6, 1 + x^2 + x^3 + x^5 + x^6, 1 + x +x^4> + x^5 + x^6, 1 + x^2 + x^4 + x^5 + x^6}>> ***** The right side is a list of irreducible polynomials which isassigned> to {S_1, S_2,.... S_14}.*******>> For example instead of putting this large expression (1 + x) (1 + x +x^2)> (1 + x + x^3) (1 + x + x^6) (1 + x^3 + x^6) (1 + x + x^2 + x^4 + x^6) (1+> x + x^3 + x^4 + x^6) (1 + x + x^2 + x^5 + x^6) in my table I can write itin> tems of S_i's in this form S_1 S_2 S_3 S_4 S_5 S_6 S_7 S_8.>> I tried ReplaceAll but it changes i.e. the above example to S_1(S_1+x^3)> (S_1+x_6) .... Which is not what I want.>> Can anybody tell me how to do this.> CHEKAD>> ==== Chekad, Try thismypoly = {1 + x, 1 + x + x^2, 1 + x + x^3, 1 + x^2 + x^3, 1 + x + x^6, 1 + x^3 + x^6, 1 + x + x^2 + x^4 + x^6, 1 + x + x^3 + x^4 + x^6, 1 +x^5 + x^6, 1 + x + x^2 + x^5 + x^6, 1 + x^2 + x^3 + x^5 + x^6, 1 + x + x^4+ x^5 + x^6, 1 + x^2 + x^4 + x^5 + x^6};mysub = {S_1, S_2, S_3, S_4, S_5, S_6, S_7, S_8, S_9, S_10, S_11, S_12, S_13, S_14};In[4]:=ReplacePart[mypoly, mysub, Partition[Range[Length[mypoly]], 1], Partition[Range[Length[mypoly]], 1]]Out[4]={S_, 2 S_, 3 S_, 4 S_, 5 S_, 6 S_, 7 S_, 8 S_, 9 S_, 10 S_, 11 S_, 12 S_, 13 S_}Brian> I have a question regarding substitute of an expression with index> variables..I need to make a table for some products of irreducible> polynomials (Irreducible factors of x^63 -1) . But they are so large and I> can't fit them into the columns of my table. So I need to use these> substitutions> {S_1, S_2, S_3, S_4, S_5, S_6, S_7, S_8, S_9, S_10, S_11, S_12, S_13, S_14}> : ------> {1 + x, 1 + x + x^2, 1 + x + x^3, 1 + x^2 + x^3, 1 + x + x^6,> 1 + x^3 + x^6, 1 + x + x^2 + x^4 + x^6, 1 + x + x^3 + x^4 + x^6, 1 +> x^5 + x^6, 1 + x + x^2 + x^5 + x^6, 1 + x^2 + x^3 + x^5 + x^6, 1 + x + x^4> + x^5 + x^6, 1 + x^2 + x^4 + x^5 + x^6}> > ***** The right side is a list of irreducible polynomials which is assigned> to {S_1, S_2,.... S_14}.*******> For example instead of putting this large expression (1 + x) (1 + x + x^2)> (1 + x + x^3) (1 + x + x^6) (1 + x^3 + x^6) (1 + x + x^2 + x^4 + x^6) (1 +> x + x^3 + x^4 + x^6) (1 + x + x^2 + x^5 + x^6) in my table I can write it in> tems of S_i's in this form S_1 S_2 S_3 S_4 S_5 S_6 S_7 S_8.> I tried ReplaceAll but it changes i.e. the above example to S_1 (S_1+x^3)> (S_1+x_6) .... Which is not what I want.> Can anybody tell me how to do this.> CHEKADReply-To: kuska@informatik.uni-leipzig.de ==== Withrepl = Reverse /@ Reverse[ {S1, S2, S3, S4, S5, S6, S7, S8, S9, S10, S11, S12, S13} ->{1 + x,1 + x + x^2,1 + x + x^3,1 + x^2 + x^3,1 + x + x^6,1 + x^3 + x^6,1 + x + x^2 + x^4 + x^6,1 + x + x^3 + x^4 + x^6,1 + x^5 + x^6,1 + x + x^2 + x^5 + x^6,1 + x^2 + x^3 + x^5 + x^6,1 + x + x^4 + x^5 + x^6,1 + x^2 + x^4 + x^5 + x^6} // Thread];andexpr = (1 + x) (1 + x + x^2)(1 + x + x^3) (1 + x + x^6) (1 + x^3 + x^6)(1 + x + x^2 + x^4 + x^6) (1 + x + x^3 + x^4 + x^6) (1 + x + x^2 +x^5 + x^6);expr /. replgivesS1 S10 S2 S3 S5 S6 S7 S8Since ReplaceAll[] tkae the first rule that match, you have to forceReplaceAll[] to try the longer polynomials first, and soThe first rule in repl must be1 + x^2 + x^4 + x^5 + x^6 -> S13and *not*1 + x -> S1 Jens> I have a question regarding substitute of an expression with index> variables..I need to make a table for some products of irreducible> polynomials (Irreducible factors of x^63 -1) . But they are so large and I> can't fit them into the columns of my table. So I need to use these> substitutions> {S_1, S_2, S_3, S_4, S_5, S_6, S_7, S_8, S_9, S_10, S_11, S_12, S_13, S_14}> : ------> {1 + x, 1 + x + x^2, 1 + x + x^3, 1 + x^2 + x^3, 1 + x + x^6,> 1 + x^3 + x^6, 1 + x + x^2 + x^4 + x^6, 1 + x + x^3 + x^4 + x^6, 1 +> x^5 + x^6, 1 + x + x^2 + x^5 + x^6, 1 + x^2 + x^3 + x^5 + x^6, 1 + x + x^4> + x^5 + x^6, 1 + x^2 + x^4 + x^5 + x^6}> ***** The right side is a list of irreducible polynomials which is assigned> to {S_1, S_2,.... S_14}.*******> For example instead of putting this large expression (1 + x) (1 + x + x^2)> (1 + x + x^3) (1 + x + x^6) (1 + x^3 + x^6) (1 + x + x^2 + x^4 + x^6) (1 +> x + x^3 + x^4 + x^6) (1 + x + x^2 + x^5 + x^6) in my table I can write it in> tems of S_i's in this form S_1 S_2 S_3 S_4 S_5 S_6 S_7 S_8.> I tried ReplaceAll but it changes i.e. the above example to S_1 (S_1+x^3)> (S_1+x_6) .... Which is not what I want.> Can anybody tell me how to do this.> CHEKAD ==== >I am trying to generate a list of numbers where the number being>calculated is dependant on the previous list member. >>What I (think I) need is a function, like>SeriesTable[expr,{InitialValue,imax}] where IntitialValue will be the>first value in the list and expr will be evaluated on this value to>form the second value and so on Imax times.Look at the function NestListNestList[f, iV, 3]{iV, f[iV], f[f[iV]], f[f[f[iV]]]}Bob HanlonChantilly, VA USA ==== >I need to create the following list:>>{{equation1, equation2,...equation_n},{x1,x1_0},{x2,x2_0},...{xn,xn_0}}> In[48]:= Append[{{equation1, equation2}}, List[{x1, x1_0}, {x2, x2_0}]]>Out[48]= {{equation1, equation2}, {{x1, 0}, {x2, 0}}}>>doesn't give the desired result which is>>Out[]= {{equation1, equation2}, {x1, x1_0}, {x2, x2_0}}>without the brackets.>>Has somebody an elegant solution for this problem?>n=3; {Table[ToExpression[equation<>ToString[k]], {k,n}], Sequence@@Table[{ToExpression[x<>ToString[k]], x<>ToString[k]<>_0}, {k,n}]}{{equation1,equation2,equation3},{x1,x1_0},{x2,x2_0},{ x3,x3_0}}Bob HanlonChantilly, VA USA ==== >Construct a matrix which has symbol a in the upper left (1,1) element>>and symbols I c in the rest of the top row and the left-most column,>>dot it into itself three times, and display the result using MatrixForm.>>The top row in the display now has I c (a^2 - 4c^2) ; the left-most >column now has I a^2 c - 4 I c^3 . Not exactly a serious problem, but>>not exactly clean either. Makes it harder to see at a glance whether a>>given matrix is symmetric above the diagonal (could be a problem in a >more complicated situation). Could possibly mess up the behavior of >pattern matching rules?use Simplifym.m.m // SimplifyBob HanlonChantilly, VA USA ==== >>Construct a matrix which has symbol a in the upper left (1,1) element>>and symbols I c in the rest of the top row and the left-most column,>>dot it into itself three times, and display the result using MatrixForm.>>The top row in the display now has I c (a^2 - 4c^2) ; the left-most >>column now has I a^2 c - 4 I c^3 . Not exactly a serious problem, but>>not exactly clean either. Makes it harder to see at a glance whether a>>given matrix is symmetric above the diagonal (could be a problem in a >>more complicated situation). Could possibly mess up the behavior of >>pattern matching rules?> use Simplify> m.m.m // SimplifyOr Expand[]. It's not a MatrixForm[] thing: it's present no matter whatoutput form you use. Mathematica doesn't automatically expand products.The construction of your matrix elements proceeds by different paths (sumof products versus product of sums), so they look different.-- | John Doty You can't confuse me, that's my job.| Home: jpd@w-d.org| Work: jpd@space.mit.edu ==== Dear MathGroup Members,Tracing functions from Packages generates very longand confusing output, since long context names areprinted. To give a short example, consider the followingcommand sequence:DiscreteMath`Tree`t=MakeTree[Range[5]]Trace[ TreeFind[t,3]]generates very long output. A simple strategy to stripit would be to use Trace[command, form] which only reportsexpressions matching form.But this does not alleviate the problem that packagevariable names are very long, since all package symbolshave a long context. For examplethe private package variables Ôm' and Ôfound' are printed asDiscreteMath`Tree`Private`m andDiscreteMath`Tree`Private`foundThis makes Trace output almost unreadable.Can anyone suggest a simple idea how to remove the longcontext names in Trace output?I defined a function which cuts the context fromsymbols, but this seems awkward an application ofthe function to the output is not trivial. Johannes LudsteckReply-To: kuska@informatik.uni-leipzig.de ==== at first we need a function that strip the context and hinderthe creation of private sumbols in the global contextRemove[RemoveContextString]RemoveContextString[s_ String] := RemoveContext[s] = Module[{lst, p,str}, lst = Characters[s]; p = Position[lst, `]; If[p === {}, Return[ToExpression[s]]]; p = Last[p]; str = StringJoin @@ Drop[lst, p[[1]]]; If[MemberQ[Names[System`*], str], Print[str]; ToExpression[str], str] ]and nowPrettyTrace[trexp_]:=trexp /.s_Symbol :> HoldForm @@{RemoveContextString[ToString[s]]} /. HoldForm[s_Symbol] :> sPrettyTrace[Trace[TreeFind[t, 3]] ]will do what you want. Jens> Dear MathGroup Members,> Tracing functions from Packages generates very long> and confusing output, since long context names are> printed. To give a short example, consider the following> command sequence:> DiscreteMath`Tree`> t=MakeTree[Range[5]]> Trace[TreeFind[t,3]]> generates very long output. A simple strategy to strip> it would be to use Trace[command, form] which only reports> expressions matching form.> But this does not alleviate the problem that package> variable names are very long, since all package symbols> have a long context. For example> the private package variables Ôm' and Ôfound' are printed as> DiscreteMath`Tree`Private`m and> DiscreteMath`Tree`Private`found> This makes Trace output almost unreadable.> Can anyone suggest a simple idea how to remove the long> context names in Trace output?> I defined a function which cuts the context from> symbols, but this seems awkward an application of> the function to the output is not trivial.> Johannes Ludsteck ==== >I have a question regarding substitute of an expression with index>variables..I need to make a table for some products of irreducible>polynomials (Irreducible factors of x^63 -1) . But they are so large and>I>can't fit them into the columns of my table. So I need to use these>substitutions>>{S_1, S_2, S_3, S_4, S_5, S_6, S_7, S_8, S_9, S_10, S_11, S_12, S_13, S_14}>: ------> {1 + x, 1 + x + x^2, 1 + x + x^3, 1 + x^2 + x^3, 1 + x + x^6,> 1 + x^3 + x^6, 1 + x + x^2 + x^4 + x^6, 1 + x + x^3 + x^4 + x^6, 1>+>x^5 + x^6, 1 + x + x^2 + x^5 + x^6, 1 + x^2 + x^3 + x^5 + x^6, 1 + x +>x^4>+ x^5 + x^6, 1 + x^2 + x^4 + x^5 + x^6}>>***** The right side is a list of irreducible polynomials which is assigned>to {S_1, S_2,.... S_14}.*******>>For example instead of putting this large expression (1 + x) (1 + x +>x^2)>(1 + x + x^3) (1 + x + x^6) (1 + x^3 + x^6) (1 + x + x^2 + x^4 + x^6)>(1 +>x + x^3 + x^4 + x^6) (1 + x + x^2 + x^5 + x^6) in my table I can write>it in>tems of S_i's in this form S_1 S_2 S_3 S_4 S_5 S_6 S_7 S_8.>>I tried ReplaceAll but it changes i.e. the above example to S_1 (S_1+x^3)>(S_1+x_6) .... Which is not what I want.>>Can anybody tell me how to do this.>Reverse the order of the substitutions so that the longer expressions are replaced firstsub=Reverse[Thread[ {1+x, 1+x+x^2, 1+x+x^3, 1+x^2+x^3, 1+x+x^6, 1+x^3+x^6, 1+x+x^2+x^4+x^6, 1+x+x^3+x^4+x^6, 1+x^5+x^6, 1+x+x^2+x^5+x^6, 1+x^2+x^3+x^5+x^6, 1+x+x^4+x^5+x^6, 1+x^2+x^4+x^5+x^6}-> {S01,S02,S03,S04,S05,S06,S07,S08, S09,S10,S11,S12,S13}]];(1+x) (1+x+x^2)(1+x+x^3) (1+x+x^6)* (1+x^3+x^6) *(1+x+x^2+x^4+x^6)* (1+x+x^3+x^4+x^6)* (1+x+x^2+x^5+x^6)/.subS01 S02 S03 S05 S06 S07 S08 S10Bob HanlonChantilly, VA USA ==== I have an expression: x+y+z/(x+y)+e^(x+y)+w*x+y.... I want to replaceany (x+y) term by x no matter how the expression looks like. I tried/.command. However, it does not work properly. Is there any simple way--Xuguang(Heather) Zhang ==== I tried ReplaceRepeated, however, I got the following answer:x+y+z/(x+y)+e^(x+y)+(w*x)+y//. x+y->xe^x+x+(w*x)+2y+z/xIn fact, there is still one more (x+y) term if we rewritten the answer. That----- Original Message -----> Use ReplaceRepeated>> x+y+z/(x+y)+e^(x+y)+w*(x+y) //. x+y->x>> e^x + w*x + x + z/x> Bob Hanlon> Chantilly, VA USA>> ==== >> I tried ReplaceRepeated, however, I got the following answer:> x+y+z/(x+y)+e^(x+y)+(w*x)+y//. x+y->x>> e^x+x+(w*x)+2y+z/x>> In fact, there is still one more (x+y) term if we rewritten the answer.ThatHeather,Use Simplify with the assumption x+y=x: Simplify[x + y + z/(x + y) + e^(x + y) + w*x + y, {x + y == x}] e^x + x + w*x + z/xIn other circumstances we may have to give more help Simplify (orFullSimplify).Please check possiblities in the Help Browser.Allan---------------------Allan HayesMathematica Training and ConsultingLeicester UKwww.haystack.demon.co.ukhay@haystack.demon.co.ukVoice : +44 (0)116 271 4198Reply-To: kuska@informatik.uni-leipzig.de ==== what's wrong withIn[]:=x + y + z/(x + y) + e^(x + y) + w*x + y /. (x + y) -> qOut[]=e^q + x + w*x + 2*y + z/q?? Jens> I have an expression: x+y+z/(x+y)+e^(x+y)+w*x+y.... I want to replace> any (x+y) term by x no matter how the expression looks like. I tried> /.command. However, it does not work properly. Is there any simple way> --> Xuguang(Heather) Zhang ==== That's nice Jens, but now the z scale is different for the two plots.Similar problems also occur with a two rectangle approach. I believe thatGraphicsArray should be used less often than it is, mainly when one wants toassemble a series of plots that have the same overall plot ranges, butdifferent sets of data.If one wants to directly compare two curves or surfaces, it is better torender them in the same plot.David Parkdjmp@earthlink.nethttp://home.earthlink.net/~djmp/ BoxRatios -> {10, 10, 5}, AspectRatio -> 1/2]; Jens>> Dear experts,>> How can I force mathemathica41 to make graphics in a column of same> width but different height?> By default, mathematica gives two cells on top of each other the same> height, but arranges the width such that both cells fit in the column> width.> This results in a horizontal sequeezing/scaling of cells which I would> like to omit.>> Here is an example:> Single output of both plots one after to the other just looks fine,> but when they enter in an GraphicsArray[], the automatic scaling> squeezes the lower cell width instead of stretching its height.> demo start : just cut and paste into a new .nb >> !((( (*> demo starts here *) )([IndentingNewLine])(( plots > are shown here:>)([IndentingNewLine])> (table1 => ListPlot3D[> Table[Sin[x y], {x, 0, (3 Pi)/2, Pi/15}, {y, 0, (3> Pi)/2,> Pi/15}], PlotRange -> {0, 0.25},> Axes -> {None, None, None}, > ViewPoint -> {5, (-2.5), 0.6},> BoxRatios -> {10, 10, 1.25}];)([IndentingNewLine])> (table2 = > ListPlot3D[> Table[Sin[x y], {x, 0, (3 Pi)/2, Pi/15}, {y, 0, (3> Pi)/2,> Pi/15}], PlotRange -> {(-1), 0}, > Axes -> {None, None, None},> ViewPoint -> {5, (-2.5), 1},> BoxRatios -> {10, 10, 5}];)([IndentingNewLine])> ( graphicsarray:>)(> [IndentingNewLine])> (table3 = {{table1}, {table2}};)([IndentingNewLine])> (Show[GraphicsArray[> table3, GraphicsSpacing -> > 0]];)([IndentingNewLine])> ( width > (but different height) ? Mathematicas default is: same height, but> different > widths.>)([IndentingNewLine])> ( (* demo ends here*) ))))> demo end >> Playing around with TableForm[] or RowsEqual-> or ImageSize-> didn't> help so far. For all those of you that might have similar problems> with plotting graphics:> there are good support-procedures on the David-Park-homepage> http://home.earthlink.net/~djmp/Mathematica.html> But I couldn't find a solution for my problem.>> My general purpose is to generate an animated GIF, which shows a> 360-degree-ßy-around a surface plot, that is cut into two parts> at some z-value (this visualizes threshold effects on surfaces).> Interested people can get a copy of my *.nb>> I carefully browsed through TMB and F1HELP for GraphicsArray-Options> (well I think that F1 is pretty poor on these specific subjects),> and of course also this newsgroup, but I couln't find the magic trick> sought for.> Bye> Stef ==== Dear Colleagues,I successfully installed Packages by David Park in the past; now I got thepackage SpreadOption from Mathsource. I put SpreadOption.m in a directoryafter appending the appropriate path. So it should work. But I get: <<...OLE_Obj...>> <<...OLE_Obj...>> What has to be done?Matthias BodeSal. Oppenheim jr. & Cie. KGaAKoenigsberger Strasse 29D-60487 Frankfurt am MainGERMANYMobile: +49(0)172 6 74 95 77Internet: http://www.oppenheim.de ==== I stored my package in a folder called Personal: ...AddOnsApplicationsPersonal, or it may he ...ApplicationsAddOnsPersonals (I'm on a different computer). At any rate, the folder Personal must be in a folder that is in Mathematica's Path; the Personal folder itself must not be in the Path. You then load the package by Needs[Personal`ExcelDatFile`]; John:After putting the notebook in personal, how do you call it? I gave it a name, letÇs say Name, but I tried < ==== Fred's two solutions (both ingenious!) are simons1 and simons2 in thecode below. Allan Hayes' f5 is about ten times as fast as simons1, butsimons2 beat f5 with a p-value of 5.4% over 100 lists (for the lists of2 million that I'm using). On another trial with 200 lists, simons2 beat f5 by 8.4% with a p-valueof .00009. The % difference in Timing had the following 95% confidenceinterval:<< Statistics`ConfidenceIntervals`MeanCI[(t1 - t2)/Mean[t1]]{0.040925889018143896, 0.12796682963766004}Hence simons2 is the winner by a margin between 4% and 13%.Of course, it's possible that lists of different lengths or differentdistributions of 0's and 1's would give different results.I also replaced If with Which to get simons3. This made no realdifference, as I should have expected! (For 200 trials, I got adifference of 0.8% and a p-value of 38.3%.)BobbyNeeds[Statistics`HypothesisTests`]f1[w_] := Count[Partition[w, 2, 1], {1, 0}]f2[w_] := Count[Drop[w, -1] - Drop[w, 1], 1] (* Allan Hayes *)f3[w_] := Count[Drop[w + 2RotateRight[w], 1], 2]f4[w_] := Tr[Drop[w, -1](Drop[w, -1] - Drop[w, 1])]f5[w_] := (Tr[w] - Tr[BitAnd[w, RotateLeft[w]]]) + If[w[[1]] == 0 && w[[-1]] == 1, -1, 0] (* Carl K. Woll, Allan Hayes *)f6[w_] := (Tr[#] - Tr[# Drop[w, 1]]) &[Drop[w, -1]] (* Allan Hayes *)f7 = Compile[{{w, _Integer, 1}}, Count[Drop[w, -1] - Drop[w, 1], 1]] (* Andrzej Kozlowski *);f8[w_List] /; Last[w] == 1 && First[w] == 0 := Count[w - RotateLeft[w],1];f8[w_List] := Count[Drop[w, -1] - Drop[w, 1], 1] (* Andrzej *);f9[w_] := Count[w - RotateLeft[w], 1] (* Andrzej *)simons1[w_] := Count[ListCorrelate[{1, -1}, w], 1]simons2[lst_] := (Tr[BitXor[lst, RotateLeft[lst]]] + If[lst[[1]] == 1, 0, If[lst[[-1]] == 1, -2, 0]])/2simons3[w_] := (Tr[BitXor[w, RotateLeft[w]]] + Which[w[[1]] == 1, 0, w[[-1]] == 1, -2, True, 0])/2trial[f_, g_] := (n = 2000000; w = Table[Random[Integer], {n}]; First@Timing[#[w];]/Second & /@ {f, g} )test[f_, g_, n_Integer] := ( {t1, t2} = Transpose[trial[f, g] & /@ Range[n]]; Print[Mean /@ {t1, t2}]; Print[r = MeanTest[t1 - t2, 0, FullReport -> True]]; meanDiff = (FullReport /. r)[[1, 1, 1]]; Print[% difference = , meanDiff/Mean[t1]])test[f5, simons1, 40]{0.07045000000000243, 0.7038500000000006}{FullReport -> TableForm[{{Mean, TestStat, Distribution}, {-0.6333999999999982, -122.74356937717243,StudentTDistribution[39]}}, TableHeadings -> {None, {Mean, TestStat, Distribution}}], OneSidedPValue -> 2.1679176203297467*^-52}% difference = -8.990773598test[f5, simons2, 100]{0.06879000000000246, 0.0654299999999978}{FullReport -> TableForm[{{Mean, TestStat, Distribution}, {0.003360000000004675, 1.6229487334543304,StudentTDistribution[99]}}, TableHeadings -> {None, {Mean, TestStat, Distribution}}], OneSidedPValue -> 0.053890293563366165}% difference = 0.04884430876587519Here's timing for one list, for all 12 solutions:Timing[#[w]]/{Second, 1} & /@ {f1, f2, f3, f4, f5, f6, f7, f8, f9, simons1, simons2, simons3}{{1.266, 500515}, {0.547, 500515}, {0.5, 500515}, {0.171, 500515}, {0.063, 500515}, {0.141, 500515}, {0.14, 500515}, {0.516, 500516}, {0.515, 500516}, {0.672, 500515}, {0.047, 500515}, {0.078, 500515}}Bobby Treat-----Original Message-----No doubt the shortest and most elegant solution is found by splittingthelist into pairs and simply count the number of lists {1,0}. But thatturnsout not to be the fastest solution. The idea behind all other solutionsisto look at the sequence of successive differences and then count thenumber1. So how to find this list of differences?Two ways have been demonstrated:Drop[lst, -1] - Drop[lst, 1]Drop[lst - RotateLeft[lst], 1]These two solutions are about as fast. Andrzej Kozlowsky noted thatdroppingthe last element in the second solution is only necessary when the listhasthe structure {0, ..., 1} which for long lists may give some gain ofspeed.There is a third way, as fast as the two others:ListCorrelate[{1,-1}, lst ]The list of differences consists of the elements 1, 0 and -1. Instead ofusing Count for counting the number of ones, Carl Woll in an ingeniouswayreplaced the elements -1 by 0 and then used the trace function to countthenumber of ones. Successive improvements in the implementation of thisideabij Allan Hayes and Carl Woll lead to an amazing fast solution by AllanHayes.Still another approach is possible, based on the observation thatbetweenany two occurences of {1,0} in the list there must be an occurence of{0,1}. Therefore when the list starts with 1 and ends with 0, the numberof1's in the list of diffences is one more than the number of -1's, etc.Usingthe same techniques as developed by Carl Woll and Allan Hayes we arriveatthe following solution:(Tr[BitXor[lst, RotateLeft[lst]]] + If[lst[[1]]==1,0,If[lst[[-1]]==1, -2,0]]) / 2Here is a timing for a list of length 5 10^6, compared with Alan'ssolution:In[126]:= lst = Table[Random[Integer], {5000000}];(Tr[lst]-Tr[BitAnd[lst,RotateLeft[lst]]])+ If[lst[[1]][Equal]0&&lst[[-1]][Equal]1,-1,0]//Timing(Tr[ BitXor[lst, RotateLeft[lst]]]+ If[lst[[1]][Equal]1, 0,If[lst[[-1]][Equal]1, -2,0]]) / 2 //TimingOut[127]={1.42 Second,1249704}Out[128]={0.88 Second,1249704}Fred SimonsEindhoven University of TechnologyReply-To: ==== Jens' solution will run into problems with $IterationLimit, unless theuser also calculates values bottom-up before asking for values likePhi[1000]:Phi/@Range[1000];Phi[1000]Where Jens said: will save the function values for P[n] he meant G[n]and Phi[n], not P[n], since he didn't include a modification of thedefinition for P[n].Phi is the only function that needs this treatment, actually; G and Pare not recursive, so saving their values will be a waste of space(contrary to the solution I sent earlier). That determination isn'tentirely trivial, so be careful in general.If xsec or anything else might be left symbolic in the calculations,you'll need to add Simplify to Phi's definition, and good luck eventhen!Also, there are typos in Matthew's original definition of Phi, so thathas to be resolved (we're only guessing where the brackets belong).Finally, ListIntegrate requires a second argument, missing in Matthew'spost.Bobby-----Original Message----- Jens> Everyone,> I've been trying to recast an iterative calculation I do as a> procedural program in C as an elegant functional program in> Mathematica 4.1. The Mathematica code is much more transparent, but> the resultant execution time is more than two orders of magnitude> longer. Any suggestions would be greatly appreciated.The following is> a schematic of the problem.> There are three equations in the iteration variable, n:> G[n_] := ListIntegrate[xsec Phi[n]] Both xsec and Phi[n] are> 400 points long.> P[n_] := G[n]/(G[n]+(a constant)+D[n]) D[n] is a simple algebraic> function of n.> Phi[1] = Flux; Flux is 400 points long.> Phi{n_] := Phi[n-1] Exp[-(1-P[n-1])*xsec> The goal is to evaluate P[n_] for an n around 1000. After running, I> need to know all the values of P[n] and Phi[n] at each n from 1 to> nmax. Note, P[n] is a number and Phi[n] is 400 points long.> Currently,> Timing[P[1]] = 0.1 s> Timing[P[2]] = 0.2 s> Timing[P[5]] = 8.4 s.> I dont dare try to evaluate P[1000] as I need to do. Every time I> evaluate these functions they recalculate from scratch. I think I> need to somehow tell Mathematica to save the intermediate values.> Curious is that the calculation time is going up like n^2, not like n> as I would have thought. The equivalent procedural c-code runs in> less than 1 second to evaluate P[1000].> -Matt Rosen> --> Matthew Rosen> Harvard-Smithsonian Center for Astrophysics> Mail Stop 59> 60 Garden Street> Cambridge, MA 02138> e: mrosen@cfa.harvard.edu> o: (617) 496-7614 ==== > Jens' solution will run into problems with $IterationLimit, unless the> user also calculates values bottom-up before asking for values like> Phi[1000]:> Phi/@Range[1000];Phi[1000]> Where Jens said: will save the function values for P[n] he meant G[n]> and Phi[n], not P[n], since he didn't include a modification of the> definition for P[n].No, I mean both ! because> Phi[1] = Flux;> Phi[n_] :=Phi[n]= Phi[n-1] Exp[-(1-P[n-1])*xsec ^^^^^^^^> G[n_] := G[n]=ListIntegrate[xsec Phi[n]]> Phi is the only function that needs this treatment, actually; G and P> are not recursive, so saving their values will be a waste of space> (contrary to the solution I sent earlier). That determination isn't> entirely trivial, so be careful in general.Since I don't kow the full program, I assume that the computationalintesive function is G[] JensReply-To: ==== OK, if x is much less than y means x/y->0, then let r be that ratioand the original function transforms into F[x , y, w, z]==F[r y, y, w, z]If r->0 in this expression, that'sLimit[F[r y, y, w, z], r->0]If x=0 is a non-removable singularity of F, the Limit as r->0 willdepend on y (if it exists).If F is continuous at x=0 it's just F[0, y, w, z].If F has a removable singularity there, it's Limit[F[x, y, w, z], x->0].Bobby-----Original Message-----> substitute x->0.> Be clear on what you want, and I think the solution will becomeobvious.> Bobby> -----Original Message-----less> assumptions> Maybe the last example I gave is too simplified. In fact, the problemI> always meet with is as follows:> F(x,y,w,z) is a function of x,y,w and z where x,y,w and z are greater> than zero. I want to simplify F(x,y,w,z) under the assumption that xis> much less than y.> ----- Original Message -----> Sent: Monday, July 22, 2002 8:48 AMless> assumptions> > try:> 1 + x^2 /. {x -> 0}> It will give you the 1 you wish.> Matthias Bode.> Gesendet: Montag, 22. Juli 2002 08:11> An: mathgroup@smc.vnet.net> Betreff: Q: Simplify with much less assumptions> I have one question regarding simplify answer with assumptions. For> example, I have 1+x^2. The assumptions is x is much much less than> 1.> Therefore x^2 can be neglected under the above assumption. What I get> after simplification should be 1 only. Can anybody tell me how do> this> in Mathematica? It seems there is no much less or much greater> Heather> I think, from the general usage of the term much less than, at leastasfar as my experience, that the correct interpretation is:x/y -> 0This, of course, also suggests a way to handle the problem. If Heathercanrecast the problem from F(x,y,w,z) to F(x/y,w,z), and then evaluate thedesired expression with the limit ( desiredExpression /. {x/y -> 0} ),thenthe problem should be solved. Or did I miss something?- Eric.-- ==== ========================================================= ==== ====I'm searching for myself... If I get back before I return, pleasemake sure I stay here. ==== ==================================================== ==== ========= ====> When you say, x is much less than y, do you mean close to 0? Or close> to -Infinity? In either case, there's no good definition of simplify> unless you mean to take the Limit, and that only works if the function> has a limit at 0 or -Infinity. You can use Limit or you can simply> substitute x->0.> Be clear on what you want, and I think the solution will become obvious.> Bobby> -----Original Message-----> assumptions> Maybe the last example I gave is too simplified. In fact, the problem I> always meet with is as follows:> F(x,y,w,z) is a function of x,y,w and z where x,y,w and z are greater> than zero. I want to simplify F(x,y,w,z) under the assumption that x is> much less than y.> ----- Original Message -----> Sent: Monday, July 22, 2002 8:48 AM> assumptions> try:> 1 + x^2 /. {x -> 0}> It will give you the 1 you wish.> Matthias Bode.> Gesendet: Montag, 22. Juli 2002 08:11> An: mathgroup@smc.vnet.net> Betreff: Q: Simplify with much less assumptions> I have one question regarding simplify answer with assumptions. For> example, I have 1+x^2. The assumptions is x is much much less than> 1.> Therefore x^2 can be neglected under the above assumption. What I get> after simplification should be 1 only. Can anybody tell me how do> this> in Mathematica? It seems there is no much less or much greater> Heather> I think, from the general usage of the term much less than, at least asfar as my experience, that the correct interpretation is:x/y -> 0This, of course, also suggests a way to handle the problem. If Heather canrecast the problem from F(x,y,w,z) to F(x/y,w,z), and then evaluate thedesired expression with the limit ( desiredExpression /. {x/y -> 0} ), thenthe problem should be solved. Or did I miss something?- Eric.-- ==== ========================================================= ==== ====I'm searching for myself... If I get back before I return, pleasemake sure I stay here. ==== ==================================================== ==== ========= ====I am writing my thesis using ArticleModern style sheet in Mathematica 4.1. I have problems as below :1) I wish to make it show the page break just like the MS Excel and MS Word do. I tried by selecting the Show Page Breaks from the menu, but nothing was seen on the screen. What should i do?2) I type my text in the cell in text form. When i click Full Right Justify Selection button, all the words at the end of each line will break into two parts and go to next line.It looks like this, example : Programming becomes Programm- (initial line) ing (following line).Anybody knows how to make the words not breaking aparts showed as above?Any helps and suggestions would be highly appreciated.Shz Shz ==== ===================================================== ==== =====================of the individual or entity to which they are addressed. Any disclosure, copying,distribution and diversion contrary to the applicable export control laws andregulations including US Export Administration Regulations is strictly prohibited.and do not disclose it to others. Please notify the postmaster@hitachi.com.myof the delivery error by replying to this message and then delete it from your ==== =================================================== ==== ===========================>I have an expression: x+y+z/(x+y)+e^(x+y)+w*x+y.... I want to replace>any (x+y) term by x no matter how the expression looks like. I tried>/.command. However, it does not work properly. Is there any simple way>of doing this?Use ReplaceRepeatedx+y+z/(x+y)+e^(x+y)+w*(x+y) //. x+y->xe^x + w*x + x + z/xBob HanlonChantilly, VA USA ==== there is a simple way, try:In[80]:=expr=x+y+z/(x+y)+e^(x+y)+w*x+yexpr/.{(x+y)->s }%/.{s->x}It works here; the intermediate substitution s was made to see it at aglance.Matthias Bode-----Ursprí.b9ngliche Nachricht-----Gesendet: Donnerstag, 25. Juli 2002 10:46An: mathgroup@smc.vnet.netBetreff: Question about ReplaceI have an expression: x+y+z/(x+y)+e^(x+y)+w*x+y.... I want to replaceany (x+y) term by x no matter how the expression looks like. I tried/.command. However, it does not work properly. Is there any simple way--Xuguang(Heather) Zhang ==== I work at Gould Academy and have recently taught myself some of theMathematica scripting language. It has been my job to write functionswhich will make analyzing data in Mathematica simpler for thestudents. I have written a number of scripts which find differentregressions of data within a file easily. But, a couple of thefunctions that I have written are not doing exactly what I want themto do. One of them takes the input from a file with multiple columnsand what number columns the user wants to be included in the data asordered pairs and is suppose to output the ordered pairs which wasselected. What it does is it doesn't output anything but does set listequal to the data which it should output. This is the code I havewritten (Sorry If It Is Ugly):f is a filename x is the column which is wanted to be the x value inthe order pairs y is the y value which is wanted to be the orderedpairs. MultCol[f_, x_, y_] := Do[For[i = 1; list = {}; length = Length[Import[f, Table]], i <=length, i++, list = Append[list, {Part[Part[Import[f, Table], i], x], Part[Part[Import[f, Table], i], y]}]]MultColCleanUp[], {1}]MultColCleanUp[] := If[DigitQ[StringTake[ToString[First[list]], {2}]], list = list, list = Rest[list]]What MultColCleanUp does is if there is a title in the first part ofthe data it removes it from the list.I would like the students to be able to simply typeMultCol[filename, 1, 3] and have the data in columns 1 and 3 infilename be put together and outputted to the screen in the form ofa matrix.thing. What this script is a function which will take a part of datafrom a file. It will take data between in the form of ordered pairs inbetween the first x value entered and the second value entered. TheCode is:FilePart[f_, n_, z_] := For[i = 1; list = {}; length = Length[Import[f, Table]], i <=length, i++, If[z >= First[Part[Import[f, Table], i]] >= n, list = Append[list, Part[Import[f, Table], i]];, If[i >= length, list = list]] ] I would like for the students to be able to simply typeFilePart[filename, 3, 5] and get {{3,78}, {4,56}, {5,90}} as output.the Y values are just for example purposes.In both scripts it assigns the value of the data wanted to list, butdoes not display list to the screen as an output.some time now. ==== > I work at Gould Academy and have recently taught myself some of the > Mathematica scripting language. It has been my job to write functions > which will make analyzing data in Mathematica simpler for the > students. I have written a number of scripts which find different > regressions of data within a file easily. But, a couple of the > functions that I have written are not doing exactly what I want them > to do. One of them takes the input from a file with multiple columns > and what number columns the user wants to be included in the data as > ordered pairs and is suppose to output the ordered pairs which was > selected. What it does is it doesn't output anything but does set list > equal to the data which it should output. This is the code I have > written (Sorry If It Is Ugly): > f is a filename x is the column which is wanted to be the x value in > the order pairs y is the y value which is wanted to be the ordered > pairs. > MultCol[f_, x_, y_] := > Do[For[i = 1; list = {}; length = Length[Import[f, Table]], i <= > length, > i++, > list = > Append[list, {Part[Part[Import[f, Table], i], x], > Part[Part[Import[f, Table], i], y]}]] > MultColCleanUp[], {1}] > MultColCleanUp[] := > If[DigitQ[StringTake[ToString[First[list]], {2}]], list = list, > list = Rest[list]] >(...)MultCol[f_,x_,y_]:= Select[ Import[f, Table][[All, {x, y}]], NumberQ[First[#]]& ]should work. If you want to keep your Functions, you should consider using local variables:MultCol[f_,x_,y_]:=Module[{list,i}, Do[...]; list]but in my opinion it is bad style (sorry), to read the file 2*length times. To assign the result to the global variable list do:list = MultCol[f,2,5].Peter-- ==== > MultCol[f_,x_,y_]:= > Select[ Import[f, Table][[All, {x, y}]], NumberQ[First[#]]& ] > should work.(when being online again) I didn't recocnize Allan's previous post with thereally good idea to use n__ instead of x_, y_. So sorry for repeating solutions.Peter-- ==== Charles has pointed out that my previous posting gave rows and he wantedcolumns.The following gives columns.MultColumn[ß_,n___]:=Cases[Import[ß,Table],{x___? NumberQ}][[All,{n}]]Test MultColumn[ß,1,3] {{0,8},{5,3},{6,8}}We can do more: MultColumn[ß,3,1] {{8,0},{3,5},{8,6}} MultColumn[ß,3,1,3] {{8,0,8},{3,5,3},{8,6,8}}--Allan---------------------Allan HayesMathematica Training and ConsultingLeicester UKwww.haystack.demon.co.ukhay@haystack.demon.co.ukVoice : +44 (0)116 271 4198> I work at Gould Academy and have recently taught myself some of the> Mathematica scripting language. It has been my job to write functions> which will make analyzing data in Mathematica simpler for the> students. I have written a number of scripts which find different> regressions of data within a file easily. But, a couple of the> functions that I have written are not doing exactly what I want them> to do. One of them takes the input from a file with multiple columns> and what number columns the user wants to be included in the data as> ordered pairs and is suppose to output the ordered pairs which was> selected. What it does is it doesn't output anything but does set list> equal to the data which it should output. This is the code I have> written (Sorry If It Is Ugly):>> f is a filename x is the column which is wanted to be the x value in> the order pairs y is the y value which is wanted to be the ordered> pairs.>> MultCol[f_, x_, y_] :=> Do[For[i = 1; list = {}; length = Length[Import[f, Table]], i <=> length,> i++,> list => Append[list, {Part[Part[Import[f, Table], i], x],> Part[Part[Import[f, Table], i], y]}]]> MultColCleanUp[], {1}]>> MultColCleanUp[] :=> If[DigitQ[StringTake[ToString[First[list]], {2}]], list = list,> list = Rest[list]]>> What MultColCleanUp does is if there is a title in the first part of> the data it removes it from the list.>> I would like the students to be able to simply type> MultCol[filename, 1, 3] and have the data in columns 1 and 3 in> filename be put together and outputted to the screen in the form of> a matrix.>> thing. What this script is a function which will take a part of data> from a file. It will take data between in the form of ordered pairs in> between the first x value entered and the second value entered. The> Code is:>> FilePart[f_, n_, z_] :=> For[i = 1; list = {}; length = Length[Import[f, Table]], i <=> length, i++,> If[z >= First[Part[Import[f, Table], i]] >= n,> list = Append[list, Part[Import[f, Table], i]];,> If[i >= length, list = list]]> ]>> I would like for the students to be able to simply type> FilePart[filename, 3, 5] and get {{3,78}, {4,56}, {5,90}} as output.> the Y values are just for example purposes.>> In both scripts it assigns the value of the data wanted to list, but> does not display list to the screen as an output.>> some time now.> ==== Charles,Below ß contains the following Test Table 0 6 8 5 0 3 6 6 8Using MultColumn[ß_,n___]:= Cases[Import[ß, Table], {x___?NumberQ}][[{n}]]we get MultColumn[ß,1,3] {{0,6,8},{6,6,8}}PS. For and While do not generate output -- we have to add this on: n=1;While[ n<4, ++n];n 4--Allan---------------------Allan HayesMathematica Training and ConsultingLeicester UKwww.haystack.demon.co.ukhay@haystack.demon.co.ukVoice : +44 (0)116 271 4198> I work at Gould Academy and have recently taught myself some of the> Mathematica scripting language. It has been my job to write functions> which will make analyzing data in Mathematica simpler for the> students. I have written a number of scripts which find different> regressions of data within a file easily. But, a couple of the> functions that I have written are not doing exactly what I want them> to do. One of them takes the input from a file with multiple columns> and what number columns the user wants to be included in the data as> ordered pairs and is suppose to output the ordered pairs which was> selected. What it does is it doesn't output anything but does set list> equal to the data which it should output. This is the code I have> written (Sorry If It Is Ugly):>> f is a filename x is the column which is wanted to be the x value in> the order pairs y is the y value which is wanted to be the ordered> pairs.>> MultCol[f_, x_, y_] :=> Do[For[i = 1; list = {}; length = Length[Import[f, Table]], i <=> length,> i++,> list => Append[list, {Part[Part[Import[f, Table], i], x],> Part[Part[Import[f, Table], i], y]}]]> MultColCleanUp[], {1}]>> MultColCleanUp[] :=> If[DigitQ[StringTake[ToString[First[list]], {2}]], list = list,> list = Rest[list]]>> What MultColCleanUp does is if there is a title in the first part of> the data it removes it from the list.>> I would like the students to be able to simply type> MultCol[filename, 1, 3] and have the data in columns 1 and 3 in> filename be put together and outputted to the screen in the form of> a matrix.>> thing. What this script is a function which will take a part of data> from a file. It will take data between in the form of ordered pairs in> between the first x value entered and the second value entered. The> Code is:>> FilePart[f_, n_, z_] :=> For[i = 1; list = {}; length = Length[Import[f, Table]], i <=> length, i++,> If[z >= First[Part[Import[f, Table], i]] >= n,> list = Append[list, Part[Import[f, Table], i]];,> If[i >= length, list = list]]> ]>> I would like for the students to be able to simply type> FilePart[filename, 3, 5] and get {{3,78}, {4,56}, {5,90}} as output.> the Y values are just for example purposes.>> In both scripts it assigns the value of the data wanted to list, but> does not display list to the screen as an output.>> some time now.> ==== I've tracked down the slow operation of my Mathematica simulation code to lie in the ListIntegrate command:G[n_] := ListIntegrate[xsec Phi[n], 1]where both xsec and Phi[n] are 400 values long.Is there a way to speed up ListIntegrate via Compile or a similar technique?Matt---Matthew RosenHarvard-Smithsonian Center for AstrophysicsMail Stop 5960 Garden StreetCambridge, MA 02138e: mrosen@cfa.harvard.eduo: (617) 496-7614 ==== Mark,I missed out the data that was used in my previous posting.It was data = Table[{x, 100Sin[x]}, {x, 0, 100, .01}];However, a restatement might be better:For a list of y values, at x values equally spaced at h apart use TrapeziumIntegrate[{a_, r___, b_}, h_] := (a + b + 2Tr[{r}])h/2For a list of {x,y}-values with x abitrarilly spaced use: TrapeziumIntegrate[data_] := (Drop[#1, 1] - Drop[#1, -1]).(Drop[#2, -1] + Drop[#2, 1]) &[data[[All,1]], data[[All, 2]]]/2--Allan---------------------Allan HayesMathematica Training and ConsultingLeicester UKwww.haystack.demon.co.ukhay@haystack.demon.co.ukVoice : +44 (0)116 271 4198> I've tracked down the slow operation of my Mathematica simulation code to> lie in the ListIntegrate command:>> G[n_] := ListIntegrate[xsec Phi[n], 1]>> where both xsec and Phi[n] are 400 values long.>> Is there a way to speed up ListIntegrate via Compile or a similartechnique?> Matt> ---> Matthew Rosen> Harvard-Smithsonian Center for Astrophysics> Mail Stop 59> 60 Garden Street> Cambridge, MA 02138>> e: mrosen@cfa.harvard.edu> o: (617) 496-7614> ==== Mathew,Some possibilities < I've tracked down the slow operation of my Mathematica simulation code to> lie in the ListIntegrate command:>> G[n_] := ListIntegrate[xsec Phi[n], 1]>> where both xsec and Phi[n] are 400 values long.>> Is there a way to speed up ListIntegrate via Compile or a similartechnique?> Matt> ---> Matthew Rosen> Harvard-Smithsonian Center for Astrophysics> Mail Stop 59> 60 Garden Street> Cambridge, MA 02138>> e: mrosen@cfa.harvard.edu> o: (617) 496-7614> ==== I have a problem with using the function ToExpression to make a string into an expression that can then be evaluated. Something goes wrong with the evaluation - when I type the same expression in by hand, then it evaluates properly. Either I am totally off in my understanding of how ToExpression works, or there is a potential bug (I am using version (sheubac@calstatela.edu) rather than to the mathgroup, as I am travelling and cannot subscribe to the mathgroup right now - it would Silvia ******************************** i = {1, 0, 0}; j = {0, 1, 0}; k = {0, 0, 1}; zero = {0, 0, 0}; a = {i, j, k} str1 = (((..)(..))(..)) The function insertx is to convert this string of parentheses and dots into a cross product, where each dot represents a different variable, and the parentheses indicate the groupings of the cross product. insertx[str_] := Module[{foo = str, vars, n, pos}, foo = StringReplace[ foo, {)( -> ),(, .( -> .,(, ). -> ),., .. -> .,.}]; foo = StringReplace[foo, {) -> ], ( -> Cross[}]; n = Length[StringPosition[foo, .]]; Do[pos = StringPosition[foo, .][[1]]; foo = StringReplacePart[foo, ToString[Slot[i]], pos] (*Print[foo]*) , {i, n}]; ToExpression[foo]] The function properly converts the string into the associated cross product, but does not evaluate correctly. Checking whether what is returned by the function is still a string gives a false, and it should, as the function should return an expression. (the output is indented) insertx[str1] ((#1[Cross]#2)[Cross](#3[Cross]#4))[Cross](#5[Cross ]#6) insertx[str1] &[j, k, i, k, k, i] ((#1[Cross]#2)[Cross](#3[Cross]#4))[Cross](#5[Cross ]#6) StringQ[insertx[str1]] False Typing in the corresponding cross product by hand and evaluating it returns the correct result. Cross[Cross[Cross[#1, #2], Cross[#3, #4]], Cross[#5, #6]] &[j, k, i, k, k, i] {1, 0, 0} What is wrong??? I have spent many hours on trying to understand this, so either I am completely off or there is a bug. ==== Heather,This could be a solution.At first, the expression should be treated as text, in which the stringx+y would be replaced by the string x. The result should then be turnedagain into an expression. In[] expre=x+y+z/(x+y)+e^(x+y)+w*x+yOut[] e^(x + y) + x + w x + 2 y + z/(x + y)In[] expretxt=x+y+z/(x+y)+e^(x+y)+w*x+yOut[] x+y+z/(x+y)+e^(x+y)+w*x+yIn[] ToExpression[StringReplace[ expretxt,x+y->x]]Out[] e^x + x + w x + z/xI was not able to keep the expression ordered as entered. In fact, if wemanually write the solution, the output obtained is also sorted in thisconvenient way. I tried Hold and HoldForm.In[]:=sol=x+z/x+e^x+w*xOut[]=e^x + x + w x + z/xJulio----- Original Message -----> Xuguang(Heather) Zhang> ==== Heather,It works.x + y + z/(x + y) + e^(x + y) + w*x + y /. x + y -> xe^x + x + w*x + 2*y + z/x2y so there is no replacement there.But generally you will have to use ReplaceRepeated (//.).x + y + z/(x + y) + e^(x + y) + w*(x + y) //. x + y -> xe^x + x + w*x + z/xDavid Parkdjmp@earthlink.nethttp://home.earthlink.net/~djmp/ Sender: steve@smc.vnet.netApproved: Steven M. Christensen , Moderator ==== I downloaded the SpreadOptions package and modified it so that it will worklike a standard package. The package file is attached. (Other readers canmodify the package as I describe below.)To use it, create a new Finance folder in ExtraPackages. Put theSpreadOption.m file there. Then you can simply load the package with:Needs[Finance`SpreadOption`]All I did was change the name of the package in the BeginPackage statementto Finance`SpreadOption. Anyone can do this by editing the package file.This, it seems to me, is the method that should be used for third partypackages. If this method is used, the packages behave just like standardpackages. However, probably because it is not clearly presented in the WRIdocumentation, very few people use the method. The result is a lot ofconfusion in connecting to packages. Also, it seems to me that packagesshould be in a standard place and the StandardPackages and ExtraPackgesfolders that WRI provides are those places.David Parkdjmp@earthlink.nethttp://home.earthlink.net/~djmp/ Sal. Oppenheim jr. & Cie. KGaAKoenigsberger Strasse 29D-60487 Frankfurt am MainGERMANYMobile: +49(0)172 6 74 95 77Internet: http://www.oppenheim.de filename=SpreadOption.m(* :Title: Spread Option Pricing Model *)(* :Author: Espen Gaarder Haug *)(* :Summary: Calculates the value for European call and put options on the difference between two utures contracts, better known as spread options.*)(* :Context: SpreadOption` *)(* :Copyright: Copyright (c) 1999 Espen Gaarder Haug *)(* :Keywords:option pricing, spread option, financial derivatives, crack spread options,spark spread options.*)BeginPackage[Finance`SpreadOption`](* Usage Statments and Description *)SpreadOption::usage =The SpreadOption package implemented by Espen Gaarder Haug(the author of ÔThe Complete Guide to Option Pricing Formulas') can beused for valuation and sensitivity analysis of European spread optionson futures and forward contracts.Functions included are:SpreadOption calculates the spread option value, SpreadOptionDelta1 andSpreadOptionDelta2 calculates the Delta values, SpreadOptionGamma1 andSpreadOptionGamma2 calculates the Gamma values, SpreadOptionVega1 andSpreadOptionVega2 calculates the Vega values, SpreadOptionThetacalculates the Theta value, SpreadOptionRho calculates the Rho values, andSpreadOptionCor calculates the sensitivity for changes in thecorrealtion coeficient,A call spread option on two futures contracts will at maturity payMax[F1-F2-X,0], where F1 is the price of future one at maturity,and F2 is the price of future two at maturity, X is the strike price.Similarly the payoff from a put spread option is Max[X-F1+F2,0].Spread options are popular in many markets, and especially in theenergy markets. At New York Mercantile Exchange spread options aretraded on the spread/difference between heating oil and crude oil, as wellas between gasoline and crude oil. These are better known as crack spread options.With the deregulation of the electricity/power markets around the world,hedgers and risk takers are now also doing options on the price differencebetween oil and electricity. In the energy market such optionsare known as spark spread options.The valuation formula here assumes a Black-Scholes world, that is the futureprice follows a geometric Brownian motion (the future prices areLog-normal distributed etc.). Since the option is on two future contracts,that means two correlated geometric Brownian motions.The implementation is based on the formula published by: Kirk, E. 1995:'Correlation in the Energy Markets,' in Managing Energy Price Risk. London:Risk Publications and Enron, 71-78. This is actually an approximation, butit is very accurate with respect to all practical purposes. More informationon valuation of both European and American style spread options can be foundin: Haug, E. G. 1997: ÔThe Complete Guide To Option Pricing Formulas,'SpreadOptionDelta1::usage =SpreadOptionDelta1[CPFlag, F1, F2, X, T, r, v1, v2, rho] calculates the delta-one for a European spread option. That is the the change in option value fora small change in future contract one (F1).CPFLag=1 for call option, -1 for put option.A call spread option on two futures contracts will at maturity payMax[F1-F2-X,0], where F1 is the price of future one at maturity, and F2 isthe price of future two at maturity, X is the strike price. Similarly the payoff from a put spread option is Max[X-F1+F2,0]. T=time to maturity in years,r=risk-free interest rate, v1=volatility of future contract one,v2=volatility of future contract two, rho=correlation between thereturn of the two futures contractsSpreadOptionDelta2::usage =SpreadOptionDelta2[CPFlag, F1, F2, X, T, r, v1, v2, rho] calculates the delta-two for a European spread option. That is the change in option value for a small change in future contract two (F2).CPFLag=1 for call option, -1 for put option.A call spread option on two futures contracts will at maturity payMax[F1-F2-X,0], where F1 is the price of future one at maturity, and F2 isthe price of future two at maturity, X is the strike price. Similarly the payoff from a put spread option is Max[X-F1+F2,0]. T=time to maturity in years,r=risk-free interest rate, v1=volatility of future contract one,v2=volatility of future contract two, rho=correlation between thereturn of the two futures contractsSpreadOptionGamma1::usage =SpreadOptionGamma1[ F1, F2, X, T, r, v1, v2, rho] calculates theGamma-one for a European spread option. That is the second derivatives of theoption value with respect to future contract one (F1).Same for call and put.A call spread option on two futures contracts will at maturity payMax[F1-F2-X,0], where F1 is the price of future one at maturity, and F2 isthe price of future two at maturity, X is the strike price. Similarly the payoff from a put spread option is Max[X-F1+F2,0]. T=time to maturity in years,r=risk-free interest rate, v1=volatility of future contract one,v2=volatility of future contract two, rho=correlation between thereturn of the two futures contractsSpreadOptionGamma2::usage =SpreadOptionGamma2[ F1, F2, X, T, r, v1, v2, rho] calculates theGamma-two for a European spread option. That is the second derivatives of theoption value with respect to future contract two (F2).Same for call and put.A call spread option on two futures contracts will at maturity payMax[F1-F2-X,0], where F1 is the price of future one at maturity, and F2 isthe price of future two at maturity, X is the strike price. Similarly the payoff from a put spread option is Max[X-F1+F2,0]. T=time to maturity in years,r=risk-free interest rate, v1=volatility of future contract one,v2=volatility of future contract two, rho=correlation between thereturn of the two futures contractsSpreadOptionVega1::usage =SpreadOptionVega1[ F1, F2, X, T, r, v1, v2, rho] calculates theVega-one for a European spread option. That is the first derivatives of theoption value with respect to the volatility of futures contract one (v1).The Vega number have been divided by 100 to get it for percent point changes(the practical market Ôstandard').Same for call and put.A call spread option on two futures contracts will at maturity payMax[F1-F2-X,0], where F1 is the price of future one at maturity, and F2 isthe price of future two at maturity, X is the strike price. Similarly the payoff from a put spread option is Max[X-F1+F2,0]. T=time to maturity in years,r=risk-free interest rate, v1=volatility of future contract one,v2=volatility of future contract two, rho=correlation between thereturn of the two futures contractsSpreadOptionVega2::usage =SpreadOptionVega2[ F1, F2, X, T, r, v1, v2, rho] calculates theVega-two for a European spread option. That is the first derivatives of theoption value with respect to the volatility of futures contract two (v2).The Vega number have been divided by 100 to get it for percent point changes(the practical market Ôstandard').Same for call and put.A call spread option on two futures contracts will at maturity payMax[F1-F2-X,0], where F1 is the price of future one at maturity, and F2 isthe price of future two at maturity, X is the strike price. Similarly the payoff from a put spread option is Max[X-F1+F2,0]. T=time to maturity in years,r=risk-free interest rate, v1=volatility of future contract one,v2=volatility of future contract two, rho=correlation between thereturn of the two futures contractsSpreadOptionTheta::usage =SpreadOptionTheta[CPFlag, F1, F2, X, T, r, v1, v2, rho] calculates theTheta value for a European spread option. That is partial derivatives of the option valuewith respect to time to expiration (T).The Theta number have been divided by 365 to get it on a daily basis. I have also taken the minus value of the partial derivatives. This because we always get closer to expiration, time moves in one direction. That is the theta value that comes out is a approximation for what will happen with the option value as you get one day closer to maturity (the market Ôstandard').CPFLag=1 for call option, -1 for put option.A call spread option on two futures contracts will at maturity payMax[F1-F2-X,0], where F1 is the price of future one at maturity, and F2 isthe price of future two at maturity, X is the strike price. Similarly the payoff from a put spread option is Max[X-F1+F2,0]. T=time to maturity in years,r=risk-free interest rate, v1=volatility of future contract one,v2=volatility of future contract two, rho=correlation between thereturn of the two futures contractsSpreadOptionRho::usage =SpreadOptionRho[CPFlag, F1, F2, X, T, r, v1, v2, rho] calculates theRho value for a European spread option. That is partial derivatives of the option valuewith respect to the risk-free interest rate (r).The Rho number have been divided by 100 to get it for percent point changes(the market standard).CPFLag=1 for call option, -1 for put option.A call spread option on two futures contracts will at maturity pay offMax[F1-F2-X,0], where F1 is the price of future one at maturity, and F2 isthe price of future two at maturity, X is the strike price. Similarly the payoff from a put spread option is Max[X-F1+F2,0]. T=time to maturity in years,r=risk-free interest rate, v1=volatility of future contract one,v2=volatility of future contract two, rho=correlation between thereturn of the two futures contractsSpreadOptionCor::usage =SpreadOptionCor[F1, F2, X, T, r, v1, v2, rho] calculates thethe first derivatives of the option value with respect to the correaltioncoefficient (Rho). The partial derivatives have then been divided by 10 toget it for a 0.1 change in correlation.Same for call and put.A call spread option on two futures contracts will at maturity pay offMax[F1-F2-X,0], where F1 is the price of future one at maturity, and F2 isthe price of future two at maturity, X is the strike price. Similarly the payoff from a put spread option is Max[X-F1+F2,0]. T=time to maturity in years,r=risk-free interest rate, v1=volatility of future contract one,v2=volatility of future contract two, rho=correlation between thereturn of the two futures contractsBegin[`Private`]cnd[z_] := (1 + Erf[z / Sqrt[2]]) / 2;vv[F1_,F2_,X_,v1_,v2_,rho_]:=Sqrt[v1^2+(v2*F2/(F2+X))^2-2* rho*v1*v2*F2/(F2+X)];d1[F_,T_,r_,vv_]:=(Log[F]+vv^2/2*T)/(vv *Sqrt[T]);d2[F_,T_,r_,vv_]:= (Log[F]-vv^2/2*T)/(vv*Sqrt[T]);SpreadOption[CPFlag_,F1_,F2_, X_,T_,r_,v1_,v2_,rho_]:= CPFlag*(F2+X)* Exp[-r*T]*(F1/(F2+X)*cnd[CPFlag*d1[F1/(F2+X),T,r,vv[F1,F2, X,v1,v2,rho]]]- cnd[CPFlag*d2[F1/(F2+X),T,r,vv[F1,F2,X,v1,v2,rho]]]); SpreadOptionDelta1[CPFlag_,F1_,F2_,X_,T_,r_,v1_,v2_,rho_]= Evaluate[D[SpreadOption[CPFlag,F1,F2,X,T,r,v1,v2,rho], F1]];SpreadOptionDelta2[CPFlag_,F1_,F2_,X_,T_,r_,v1_,v2_,rho _]=Evaluate[D[SpreadOption[CPFlag,F1,F2,X,T,r,v1,v2,rho], F2]];SpreadOptionGamma1[F1_,F2_,X_,T_,r_,v1_,v2_,rho_]= Evaluate[D[SpreadOption[1,F1,F2,X,T,r,v1,v2,rho], {F1,2}]];SpreadOptionGamma2[F1_,F2_,X_,T_,r_,v1_,v2_,rho_]= Evaluate[D[SpreadOption[1,F1,F2,X,T,r,v1,v2,rho], {F2,2}]];SpreadOptionVega1[F1_,F2_,X_,T_,r_,v1_,v2_,rho_]= Evaluate[D[SpreadOption[1,F1,F2,X,T,r,v1,v2,rho], v1]/100];SpreadOptionVega2[F1_,F2_,X_,T_,r_,v1_,v2_,rho_]= Evaluate[D[SpreadOption[1,F1,F2,X,T,r,v1,v2,rho], v2]/100];SpreadOptionTheta[CPFlag_,F1_,F2_,X_,T_,r_,v1_,v2_, rho_]=Evaluate[-D[SpreadOption[CPFlag,F1,F2,X,T,r,v1,v2,rho], T]/365];SpreadOptionRho[CPFlag_,F1_,F2_,X_,T_,r_,v1_,v2_,rho_ ]=Evaluate[D[SpreadOption[CPFlag,F1,F2,X,T,r,v1,v2,rho], r]/100];SpreadOptionCor[F1_,F2_,X_,T_,r_,v1_,v2_,rho_]= Evaluate[D[SpreadOption[1,F1,F2,X,T,r,v1,v2,rho], rho]/100];End[]EndPackage[] ==== ** mean some sort oflink, like in {a1, a2}, and not a minus sign. Then, first construct yourelements properly:In[1]:=let = ToString /@ {a, b, c, d, e, f, g, h, i, j, k, l, m, n, o}Out[1]={a, b, c, d, e, f, g, h, i, j, k, l, m, n, o}In[2]:=num = ToString /@ {1, 2} ==== Dear Mathematica UsersRecently we were confonted with strange error messages during data OUTPUT(with Put or OpenWrite, Export and so on).The error message was like:export:: noopen: could not open file ...It seems that with all these terms the problem lies always in the fileopening procedure.Has ANYONE experienced similar problems and does anyone know how to solveit??ThanxReply-To: kuska@informatik.uni-leipzig.de ==== on a MS-Windows box ? Put[someDirectory/someFile.m] instead ofPut[someDirectorysomeFile.m] or the directory does not exist, or or hard drive is full, or you are quotedon a unix box, or you try to write with out permission, or a filename that can't be used this~file on unixor this+file on a Windows box .. Jens> Dear Mathematica Users> Recently we were confonted with strange error messages during data OUTPUT> (with Put or OpenWrite, Export and so on).> The error message was like:> export:: noopen: could not open file ...> It seems that with all these terms the problem lies always in the file> opening procedure.> Has ANYONE experienced similar problems and does anyone know how to solve> it??> Thanx> Reply-To: ==== Here's a slightly different solution that you may find useful.expr = {1 + x, 1 + x + x^2, 1 + x + x^3, 1 + x^2 + x^3, 1 + x + x^6, 1 + x^3 + x^6, 1 + x + x^2 + x^4 + x^6, 1 + x + x^3 + x^4 + x^6, 1 + x^5 + x^6, 1 + x + x^2 + x^5 + x^6, 1 + x^2 + x^3 + x^5 + x^6, 1 + x + x^4 + x^5 + x^6, 1 + x^2 + x^4 + x^5 + x^6}; sub = Reverse[Thread[expr -> Table[((Remove[#1]; Symbol[#1]) & ) [StringJoin[S, ToString[i]]], {i, 1, 13}]]]; expr /. SubBobby Treat-----Original Message----->>{S_1, S_2, S_3, S_4, S_5, S_6, S_7, S_8, S_9, S_10, S_11, S_12, S_13,S_14}>: ------> {1 + x, 1 + x + x^2, 1 + x + x^3, 1 + x^2 + x^3, 1 + x +x^6,> 1 + x^3 + x^6, 1 + x + x^2 + x^4 + x^6, 1 + x + x^3 + x^4 + x^6, 1>+>x^5 + x^6, 1 + x + x^2 + x^5 + x^6, 1 + x^2 + x^3 + x^5 + x^6, 1 + x +>x^4>+ x^5 + x^6, 1 + x^2 + x^4 + x^5 + x^6}>>***** The right side is a list of irreducible polynomials which isassigned>to {S_1, S_2,.... S_14}.*******>>For example instead of putting this large expression (1 + x) (1 + x +>x^2)>(1 + x + x^3) (1 + x + x^6) (1 + x^3 + x^6) (1 + x + x^2 + x^4 + x^6)>(1 +>x + x^3 + x^4 + x^6) (1 + x + x^2 + x^5 + x^6) in my table I can write>it in>tems of S_i's in this form S_1 S_2 S_3 S_4 S_5 S_6 S_7 S_8.>>I tried ReplaceAll but it changes i.e. the above example to S_1(S_1+x^3)>(S_1+x_6) .... Which is not what I want.>>Can anybody tell me how to do this.>Reverse the order of the substitutions so that the longer expressionsare replaced firstsub=Reverse[Thread[ {1+x, 1+x+x^2, 1+x+x^3, 1+x^2+x^3, 1+x+x^6, 1+x^3+x^6, 1+x+x^2+x^4+x^6, 1+x+x^3+x^4+x^6, 1+x^5+x^6, 1+x+x^2+x^5+x^6, 1+x^2+x^3+x^5+x^6, 1+x+x^4+x^5+x^6, 1+x^2+x^4+x^5+x^6}-> {S01,S02,S03,S04,S05,S06,S07,S08, S09,S10,S11,S12,S13}]];(1+x) (1+x+x^2)(1+x+x^3) (1+x+x^6)* (1+x^3+x^6) *(1+x+x^2+x^4+x^6)* (1+x+x^3+x^4+x^6)* (1+x+x^2+x^5+x^6)/.subS01 S02 S03 S05 S06 S07 S08 S10Bob HanlonChantilly, VA USA ==== Is anyone here familiar with J/Link, the new and promising (if at themoment totally maddening) interface between Mathematica and java? It seemsfew sample programs have been written, there are no debugging features,and little real documentation.If so, I have a number of questions for you...Antonio GarciaBerkeley Physics (and RAND Corporation, at times...) ==== I have used J/Link for Mathematica 4.2 under Mac OS X; and Mathematica 4.1under WinXPI followed the instructions for installation as per the readme and in theAddons section of the Help Browser. I added JLink.jar to my CLASSPATH asindicated.I ran the .NBs in the Examples/Part1 folder and they worked as advertised.A Ôlil slow I might add. But they did work.In the folder Examples/Part2 (java programs that call on Mathematicainstead), I compiled the SampleProgram.java in there and worked asadvertised. Make sure you look at the .java file for the the runninginstructions for this and all the other samples in this directory.Hey, I'm with you, lack of documentation, a debugger, and better samples areneeded. If you at least want to see how J/Link works and try to tease outwhat's happening you can look at the JLink/source directory. As J/Linkmakes heavy use of Java's reßection mechanism it should be possible(Wolfram, are you listening?) possible to make a workable debugger forJ/Link.As I do a lot more programming and work in the Win environment, for me,personally, Java-anything is no longer in my scope. I really want betterCOM/ActiveX connectivity to Mathematica so I can at least go in withC++/COM...and dare I dream C#/COM-interop.>> Is anyone here familiar with J/Link, the new and promising (if at the> moment totally maddening) interface between Mathematica and java? It seems> few sample programs have been written, there are no debugging features,> and little real documentation.>> If so, I have a number of questions for you...>> Antonio Garcia> Berkeley Physics (and RAND Corporation, at times...)>> ==== I'm having a frustrating problem drawing a 3D curve with a dashed line.It seems that in Graphics3D *unlike* Graphics, a Line composed of manyshort segments can't properly be drawn with a dashing pattern. I can onlyget it to work by decimating the list of points along the curve, which isnot a good solution. Has someone developed a better solution? Below Iillustrate this problem with a simple example.ScottWe define simple functions to generate tables of n points in a circlecirctab2d[n_]:=Table[{Sin[2 Pi x],Cos[2 Pi x]},{x,0,1,1/n}]circtab3d[n_]:=Table[{Sin[2 Pi x],Cos[2 Pi x],0},{x,0,1,1/n}]In (2D) Graphics, we can draw a nice dashed polyline (in this case, acircle) with as many segments as we want:Show[ Graphics[{ Dashing[{0.03}], Line[circtab2d[350]] }], AspectRatio->Automatic];However, in Graphics3D, our line segments apparently need to be at leastas long as the dashing period in order to be drawn properly. In thisexample, we need to keep the number of segments to about 30 or less to berendered properly. Very short segments (e.g. 350) will result in a solidline without dashing. This is true for both on-screen display and printedPostScript output.Show[ Graphics3D[{ Dashing[{0.03}], Line[circtab3d[35]] }], AspectRatio->Automatic]; ==== I'd like to change the default settings of the File>Printing Settings> the header in all future notebooks.I know how to do this in individual notebooks, so I opened Default.nb, made this change, and Quit and re-Opened Mathematica. The change seems to stick in Default.nb, but still doesn't seem to show up in new notebooks.??? ==== > On a related note, I notice that the new 4.2 truetype fonts still have> their internal font-rights-privileges ßags set to editable> rather than installable, which plays havoc with attempts to embed> such fonts within external docs (such as Adobe Distiller working on> Mathematica-exported graphics). The commercial Font Creator Program allows one> to readily modify these font files by ßipping this ßag (which from> earlier interactions was fine by WRI).In response to a query on exactly *how* to use Font Creator Program(FCP) to do the above: 1. Open the font file 2. On the menu bar, pulldown General->Metrics...this opens theMetrics window. 3. Be sure the General tab on Metrics window is selected. 4. In the center-right of window is the field Font EmbeddingLicensing Rights -- pulldown/select Installable. 5. Then okay, then save the file. ====