A102 === Subject: Packages without packages > Yet I'd like to explain better what is my larger problem is: > to break down a big project in pieces, it is correct then to save big > chunks of code definitions as packages? In my musing on packages, I've been thinking that I tend to have a fair number of individual projects on different physical topics, which I keep in individual folders or directories, and each of which tends to have its own set of project-specific modules or packages. And, my packages in fact consist almost totally of just Module definitions, sometimes lengthy, which implement some complicated computational algorithm or create some plot or table generally specific to that project. So, why futz with the complexity of Mathematica's global package mechanism at all? How about a packages without packages approach. For each project, I typically have one or a few project notebooks which, essentially, explore physics questions and prepare reports or memos or documents that I file or send to others (and in which I may want to present a lot of graphic or tabular results, with a lot of associated commentary, but very little detailed code). So, why not associate with each project a ProjectModules.nb notebook which contains nothing but the definitions of any major or lengthy Modules or := formula definitions tht I use in that project's notebooks. This ProjectModules.nb notebook **can reside right in the folder for that project** -- in fact, it can be open all the time I'm working on any of the notebooks for that project, with its window minimized. If I decide I want to reformat a graphic that is created in one of those project notebooks by a certain Module, I can open ProjectModules.nb window, do the editing of that Module, and re-execute the whole notebook very quickly (it doesn't _do_ any work when re=executed; just redefines stuff). Shifting over to work on a different project? Just open the folder for that project; restart Mathematica to clear out all the sludge from the previous project; execute the ProjectModules.nb in that folder; and start on whatever other notebook(s) that use those modules. I'm not knocking that basic packages concept, for those who may need it. But for me, packages without packages may offer: 1) Modularity 2) Simplicity 3) I always know what's going on. 4) Freedom from cross-project confusion 5) Freedom from the complexities of the whole package system (and from Wolfram's compulsion to keep changing it) (and from their inability to document these changes usefully) === Subject: Mathlink: How do I pass arbitrary data from Mathematica to C? I am trying to write some code to interface Mathematica to a closed- source library written in C. I'm using Mathlink for this, which is typically used to interface Mathematica to external functions - see for example For example, if the library has a function 'f' with the following prototype: int f(int x, int y); the following in a Mathlink template (.tm file) will allow me to call this function from Mathematica by the name Foo, if I link to the library., create an executable, then install that executable in Mathematica with Install[]. :Begin: :Function: f :Pattern: Foo[x_Integer, y_Integer] :Arguments: {x, y} :ArgumentTypes: {Integer, Integer} :ReturnType: Integer :End: (There is no need for me to write the function f, as that has been done. I just need to link to the library containing the function f, in much the same way you use the 'pow' function in C without writing it - you would just link to the maths library.). I have no problem with the above - it all works as expected. The problem occurs with a function 'g', which instead of having only integer arguments, takes a pointer to some data. The format of the data is not specified - the C function just needs to know where in memory the data is, and how many bytes there are. The C prototype is int g(const void *data, long nbytes); Does anyone know how I can write a Mathematica template so when I link with the function 'g', I can pass the data properly? Note, that since the library is closed-source, I am not able to change the calling method in any way. But I expect it should be possible to write an interface in C, such that data is passed from Mathematica in a form compatible with Mathematica, and then converts it to a from the C library accepts. But I am stuck as how to do this. If its not possible to do this with a template, can it be done by writing it all in C? If so, how? I don't want Mathematica to try to interpret the data in any way - just to pass an address of where the data is in memory, and also the number of bytes of data. Than the library function g will return an integer, which I want to pass back to Mathematica. Someone suggested that I might look at the C code generated by mcc to work out how to do this, (perhaps making use of MLPutInteger), but I can't work out how to do this. Does that make sense? Any ideas how to pass arbitrary data to a C program? I have a similar issue in trying to get arbitrary data from C to Mathematica, but that is another story. === Subject: Re: Mathlink: How do I pass arbitrary data from Mathematica to C? I sent a post a few minutes ago in which I said the data might be a binary file, I think I then gave the way I might read that as BinaryReadList[filename.dat,Character8] If I did (and I dont have a record of the post, which had not appeared yet), then I was wrong. I should have used BinaryReadList[filename.dat,Byte] I think. The point I need to get over is that the data format is not set in stone, so I need a way of transfering an arbitrary collection of bytes === Subject: Re: Mathlink: How do I pass arbitrary data from Mathematica to C? Unfortunately, I don't fully understand your question, but I hope the > following example of how I would use the function in C will help. I'll > call the function write_to_hardware and another read_from_hardware. I > do in fact want to use both functions in Mathematica, although I have > only asked about one so far. main() > { > void *huminity_value; I think that variable names are messed up a bit. I suppose that this should be void *result, right? > double humidity, temperature; > int days_since_calibration; > int error_code; humidity=malloc(5000); /* all data received is under 5000 bytes */ And this is result = malloc(5000); Is this correct? > error_code=write_to_hardware(RESET,5); > error_code=write_to_hardware(HUMIDITY,9); /* take a measurement of > humidity */ > error_code=read_from_hardware(result,5000); /* read humidity */ > humidity=atof(result); error_code=write_to_hardware(TEMPERATURE,11); /* take a measurement > of temperature */ > error_code=read_from_hardware(result,5000); /*read tempeature */ > temperature=atof(result); printf(humidity=%lf temperature=%lf n,humidity, temperature); } The C functions definitions are int write_to_hardware( const void *data,long length_of_command_in_bytes); > int read_from_hardware(void *data, long size_of_buffer_to_store_results); If you always work with character strings, why don't you use char * instead of void *? > In Mathematica I'd like to do something like WriteToHardware(RESET, 5) > WriteToHardware(HUMIDITY, 9); > (humidity would be a Mathematica string in this case) This is not correct Mathematica syntax. In Mathematica functions are called with f[], not f(). This Mathematica interface looks OK except that it is not necessary to pass the string length to WriteToHardware. A Mathematica string is visible as a char * and and int (its length) on the C side (see the reverse example). But the point to note is that whilst in these examples the data sent > was text, and the data received was text, this might not always be the > case. Potentially the data sent might be a binary file which > calibrates the thermometer. You still need to represent the data in some way in Mathematica. You can represent it as strings, or you can represent it as a list of integers (bytes). Probably the former will be more useful. representations. Did you take a look at the MathLink example programs? There is one for working with strings (reverse) and one for working with integer arrays (sumalist). You could use these examples as starting points. All you have to do is create C wrapper functions that call read_from_hardware() and write_to_hardware(), and make these wrapper functions accessible from Mathematica. Does that make it any clearer? > === Subject: Re: Mathlink: How do I pass arbitrary data from Mathematica to C? > > int g(const void *data, long nbytes); ... > I don't want Mathematica to try to interpret the data in any way - > just to pass an address of where the data is in memory, and also the > number of bytes of data. Than the library function g will return an > integer, which I want to pass back to Mathematica. I think that there is a misunderstanding here. Everyone has assumed in their replies that you would like to transmit the data that const void *data is pointing to between the C program and Mathematica. However, it seems to me that the data is actually handled by the C program, and *never* by Mathematica. So Mathematica should only know about very simple objects that somehow *refer to* this special object that is stored in memory by the C program (and not Mathematica). Please clarify this important point. If this is the case, then one could use a Mathematica object someObject[ptr, len], where ptr and len are integers, and encode the pointer to the data and the length of the data. Only this someObject[] object would be passed to the C program (easily achievable with .tm templates), which in turn would decode the two values (ptr and len) to obtain a pointer and a length. This would work for as long as all the someObject[] objects are constructed by the C program. But if the user examines the structure of someObject[] and tries to construct someObjects with arbitrary ptr and len values, then the C program will get some invalid pointers, and will most likely crash. So I would suggest maintaining a table on the C side, which translates some identifier (e.g. a single integer) to a (ptr, len) pair. The identifier would be used on the Mathematica side, and the C program could check for validity of identifiers before translating them to pointers, to avoid invalid pointers and crashes. === Subject: Re: Mathlink: How do I pass arbitrary data from Mathematica to C? > Does that make sense? Any ideas how to pass arbitrary data to a C > program? You won't be able to do this directly. You will have to write your own C function that converts the data from a Mathematica type to the raw data your function is expecting. This is not very difficult. Try something like this (not tested): /* MyFile.tm */ :Begin: :Function: myFunc :Pattern: MyFunc[reals:(_Real...)] :Arguments: { reals } :ArgumentTypes: Manual :ReturnType: Manual :End: /* library function to call */ extern int g(const double* theData, int theLength); void myFunc(void) { double* theData; int* theDims; char** theHeads; int theDepth; if(MLGetReal64Array(stdlink, &theData, theDims, &theHeads, &theDepth)) { int theLength = theDims[0], i, theResult; for(i = 1; i < theDepth; i++) theLength *= theDims[i]; theResult = g(theData, theLength); MLReleaseReal64Array(stdlink, theData, theDims, theHeads, theDepth); MLPutInteger(stdlink, theResult); } else MLPutSymbol(stdlink, $Failed); } === Subject: Re: Mathlink: How do I pass arbitrary data from Mathematica to C? Does that make sense? Any ideas how to pass arbitrary data to a C > program? You won't be able to do this directly. You will have to write your > own C function that converts the data from aMathematicatype to the > raw data your function is expecting. This is not very difficult. Try > something like this (not tested): /* MyFile.tm */ :Begin: > :Function: myFunc > :Pattern: MyFunc[reals:(_Real...)] > :Arguments: { reals } > :ArgumentTypes: Manual > :ReturnType: Manual > :End: > But this makes nom sence to me, as my data is not necessarily going to consist of real numbers. It might do, but I certainly dont wish to assume thst. > /* library function to call */ > extern int g(const double* theData, int theLength); > The function I am calling will have the prototype int g (void *data, int length_of_data) I did wonder if it should be treated as a collection of unsigned characters, but I'm not sure if a Mathematica String would be appropiate, as then characters like n (new line) might have some significance, which I dont want them to. === Subject: Re: Mathlink: How do I pass arbitrary data from Mathematica to C? > I am trying to write some code to interface Mathematica to a closed- > source library written in C. I'm using Mathlink for this, which is > typically used to interface Mathematica to external functions - see > for example > For example, if the library has a function 'f' with the following > prototype: int f(int x, int y); the following in a Mathlink template (.tm file) will allow me to call > this function from Mathematica by the name Foo, if I link to the > library., create an > executable, then install that executable in Mathematica with > Install[]. :Begin: > :Function: f > :Pattern: Foo[x_Integer, y_Integer] > :Arguments: {x, y} > :ArgumentTypes: {Integer, Integer} > :ReturnType: Integer > :End: (There is no need for me to write the function f, as that has been > done. I just need to link to the library containing the function f, in > much the same way you use the 'pow' function in C without writing it - > you would just link to the maths library.). I have no problem with the above - it all works as expected. The problem occurs with a function 'g', which instead of having only > integer arguments, takes a pointer to some data. The format of the > data is not specified - the C function just needs to know where in > memory the data is, and how many bytes there are. The C prototype is int g(const void *data, long nbytes); Does anyone know how I can write a Mathematica template so when I link > with the function 'g', I can pass the data properly? Note, that since > the library is closed-source, I am not able to change the calling > method in any way. But I expect it should be possible to write an > interface in C, such that data is passed from Mathematica in a form > compatible with Mathematica, and then converts it to a from the C > library accepts. But I am stuck as how to do this. If its not possible to do this with a template, can it be done by > writing it all in C? If so, how? I don't want Mathematica to try to interpret the data in any way - > just to pass an address of where the data is in memory, and also the > number of bytes of data. Than the library function g will return an > integer, which I want to pass back to Mathematica. Someone suggested that I might look at the C code generated by mcc to > work out how to do this, (perhaps making use of MLPutInteger), but I > can't work out how to do this. Does that make sense? Any ideas how to pass arbitrary data to a C > program? I have a similar issue in trying to get arbitrary data from C to > Mathematica, but that is another story. > When you pass data over MathLink, you are communicating between two processes - so no pointers can be passed. It certainly sounds as though you need to write an interface routine in C - as you suggest. Presumably you know the structure of this data, so perhaps you could transmit it from Mathematica in pieces and assemble it in the required format in the interface routine. Perhaps you should tell us the structure of this data, and how big it is. David Bailey http://www.dbaileyconsultancy.co.uk === Subject: Re: Mathlink: How do I pass arbitrary data from Mathematica to C? > I am trying to write some code to interface Mathematica to a closed- > source library written in C. I'm using Mathlink for this, which is > typically used to interface Mathematica to external functions - see > for example http://reference.wolfram.com/mathematica/tutorial/SettingUpExternalFu... For example, if the library has a function 'f' with the following > prototype: int f(int x, int y); the following in a Mathlink template (.tm file) will allow me to call > this function from Mathematica by the name Foo, if I link to the > library., create an > executable, then install that executable in Mathematica with > Install[]. :Begin: > :Function: f > :Pattern: Foo[x_Integer, y_Integer] > :Arguments: {x, y} > :ArgumentTypes: {Integer, Integer} > :ReturnType: Integer > :End: (There is no need for me to write the function f, as that has been > done. I just need to link to the library containing the function f, in > much the same way you use the 'pow' function in C without writing it - > you would just link to the maths library.). I have no problem with the above - it all works as expected. The problem occurs with a function 'g', which instead of having only > integer arguments, takes a pointer to some data. The format of the > data is not specified - the C function just needs to know where in > memory the data is, and how many bytes there are. The C prototype is int g(const void *data, long nbytes); Does anyone know how I can write a Mathematica template so when I link > with the function 'g', I can pass the data properly? Note, that since > the library is closed-source, I am not able to change the calling > method in any way. But I expect it should be possible to write an > interface in C, such that data is passed from Mathematica in a form > compatible with Mathematica, and then converts it to a from the C > library accepts. But I am stuck as how to do this. If its not possible to do this with a template, can it be done by > writing it all in C? If so, how? I don't want Mathematica to try to interpret the data in any way - > just to pass an address of where the data is in memory, and also the > number of bytes of data. Than the library function g will return an > integer, which I want to pass back to Mathematica. Someone suggested that I might look at the C code generated by mcc to > work out how to do this, (perhaps making use of MLPutInteger), but I > can't work out how to do this. Does that make sense? Any ideas how to pass arbitrary data to a C > program? I have a similar issue in trying to get arbitrary data from C to > Mathematica, but that is another story. When you pass data over MathLink, you are communicating between two > processes - so no pointers can be passed. It certainly sounds as though > you need to write an interface routine in C - as you suggest. Presumably > you know the structure of this data, so perhaps you could transmit it > from Mathematica in pieces and assemble it in the required format in the > interface routine. Perhaps you should tell us the structure of this data, and how big it is. David Baileyhttp://www.dbaileyconsultancy.co.uk The data will be passed to some hardware via a library routine written in C. For example, the first bit of data might bea command like RESET, the next might be LOADFILE The next bit of data might be a binary file. Hence I need to find a way of passing an arbitrary collection of bytes. It might be one byte, two bytes, three bytes ... up to a couple MB or so. I will know the exact length. It it was a file I wanted to send, then I assume something like data=BinaryReadList[filenane.dat,Character8] would be suitable to read it, then I would need to send the contents of 'data' But equally the data might just be a bit of text. === Subject: Re: Mathlink: How do I pass arbitrary data from Mathematica to C? a) MathLink is a protocol, i.e., it *must* transmit data b) MathLink is always buffered, i.e., you will *never* get the true address of a pointer in the Mathematica kernel c) only the kernel developer know how a data structure is organized in the kernel, i.e., a array of integers *may* be a memory block of successive integers but it can be also an array of pointers to integers d) for a general expression you have to build your own tree like structure of the Mathematica expression by setting the argument type to Manual > I am trying to write some code to interface Mathematica to a closed- > source library written in C. I'm using Mathlink for this, which is > typically used to interface Mathematica to external functions - see > for example > For example, if the library has a function 'f' with the following > prototype: int f(int x, int y); the following in a Mathlink template (.tm file) will allow me to call > this function from Mathematica by the name Foo, if I link to the > library., create an > executable, then install that executable in Mathematica with > Install[]. :Begin: > :Function: f > :Pattern: Foo[x_Integer, y_Integer] > :Arguments: {x, y} > :ArgumentTypes: {Integer, Integer} > :ReturnType: Integer > :End: (There is no need for me to write the function f, as that has been > done. I just need to link to the library containing the function f, in > much the same way you use the 'pow' function in C without writing it - > you would just link to the maths library.). I have no problem with the above - it all works as expected. The problem occurs with a function 'g', which instead of having only > integer arguments, takes a pointer to some data. The format of the > data is not specified - the C function just needs to know where in > memory the data is, and how many bytes there are. The C prototype is int g(const void *data, long nbytes); Does anyone know how I can write a Mathematica template so when I link > with the function 'g', I can pass the data properly? Note, that since > the library is closed-source, I am not able to change the calling > method in any way. But I expect it should be possible to write an > interface in C, such that data is passed from Mathematica in a form > compatible with Mathematica, and then converts it to a from the C > library accepts. But I am stuck as how to do this. If its not possible to do this with a template, can it be done by > writing it all in C? If so, how? I don't want Mathematica to try to interpret the data in any way - > just to pass an address of where the data is in memory, and also the > number of bytes of data. Than the library function g will return an > integer, which I want to pass back to Mathematica. Someone suggested that I might look at the C code generated by mcc to > work out how to do this, (perhaps making use of MLPutInteger), but I > can't work out how to do this. Does that make sense? Any ideas how to pass arbitrary data to a C > program? I have a similar issue in trying to get arbitrary data from C to > Mathematica, but that is another story. > === Subject: Re: Mathlink: How do I pass arbitrary data from Mathematica to C? On 27 Mar, 13:15, -Peer Kuska Do you have an example of this, where the format of the data is not > known in advance? Do you think this is a Mathematica problem ? It would help if there were more examples in the examples directory. There are only 1090 lines including all C files, the make file, all the templates. That's not exactly over-generous for examples. Many examples on the web use addtwo.c so are not really much additional help. I feel there needs to be a number of more complex examples. > It is up to *you* to set up your data structure. My data structure is very simple - I just want to pass potentially random data from Mathematica to the C code. I do not expect Mathematica to understand the format - just pass it. The use of String may be OK, as that is an const unsigned char (I might be wrong about the unsigned), but I'm not sure if Mathematica will handle special characters any different from others. Karen === Subject: Re: Mathlink: How do I pass arbitrary data from Mathematica to C? On 24 Mar, 06:45, -Peer Kuska a) MathLink is a protocol, i.e., it *must* transmit data Understood > b) MathLink is always buffered, i.e., you will *never* > get the true address of a pointer in the Mathematica kernel Understood > c) only the kernel developer know how a data structure is organized > in the kernel, i.e., a array of integers *may* be a memory block > of successive integers but it can be also an array of pointers > to integers OK, I can see I cant make such assumptions. > d) for a general expression you have to build your own tree like > structure of the Mathematica expression by setting the argument > type to Manual Do you have an example of this, where the format of the data is not known in advance? It *must* be considered just a collection of bytes of data. The data can be any length from one byte to about a MB. It might be binary data, but will probably be text. The data will be passed to some hardware. The format of the data depends on the hardware. Hence I just want to pass what is a collection of bytes. I cant assume they will be integers (they might be), I cant assume they will be floating point values (they might be). I am trying to write some code to interface Mathematica to a closed- > source library written in C. I'm using Mathlink for this, which is > typically used to interface Mathematica to external functions - see > for example http://reference.wolfram.com/mathematica/tutorial/SettingUpExternalFu... For example, if the library has a function 'f' with the following > prototype: int f(int x, int y); the following in a Mathlink template (.tm file) will allow me to call > this function from Mathematica by the name Foo, if I link to the > library., create an > executable, then install that executable in Mathematica with > Install[]. :Begin: > :Function: f > :Pattern: Foo[x_Integer, y_Integer] > :Arguments: {x, y} > :ArgumentTypes: {Integer, Integer} > :ReturnType: Integer > :End: (There is no need for me to write the function f, as that has been > done. I just need to link to the library containing the function f, in > much the same way you use the 'pow' function in C without writing it - > you would just link to the maths library.). I have no problem with the above - it all works as expected. The problem occurs with a function 'g', which instead of having only > integer arguments, takes a pointer to some data. The format of the > data is not specified - the C function just needs to know where in > memory the data is, and how many bytes there are. The C prototype is int g(const void *data, long nbytes); Does anyone know how I can write a Mathematica template so when I link > with the function 'g', I can pass the data properly? Note, that since > the library is closed-source, I am not able to change the calling > method in any way. But I expect it should be possible to write an > interface in C, such that data is passed from Mathematica in a form > compatible with Mathematica, and then converts it to a from the C > library accepts. But I am stuck as how to do this. If its not possible to do this with a template, can it be done by > writing it all in C? If so, how? I don't want Mathematica to try to interpret the data in any way - > just to pass an address of where the data is in memory, and also the > number of bytes of data. Than the library function g will return an > integer, which I want to pass back to Mathematica. Someone suggested that I might look at the C code generated by mcc to > work out how to do this, (perhaps making use of MLPutInteger), but I > can't work out how to do this. Does that make sense? Any ideas how to pass arbitrary data to a C > program? I have a similar issue in trying to get arbitrary data from C to > Mathematica, but that is another story. === Subject: Re: Mathlink: How do I pass arbitrary data from Mathematica to C? > Do you have an example of this, where the format of the data is not > known in advance? Do you think this is a Mathematica problem ? It is up to *you* to set up your data structure. But typedef struct Atom { int what; union { long int N; double D; struct Symbol *S; } Entry; } Atom; may do that. And your data structure may be typedef struct Expression { int what; union { Atom *atm; struct { struct Expression *First; struct Expression *Rest; } List; } Entry; } Expression; clearly you need a symbol table and more data types than long int and double, rationals and complex may be added. It *must* be considered just a collection of bytes > of data. The data can be any length from one byte to about a MB. It > might be binary data, but will probably be text. > The data will be passed to some hardware. The format of the data > depends on the hardware. Hence I just want to pass what is a > collection of bytes. I cant assume they will be integers (they might > be), I cant assume they will be floating point values (they might > be). > === Subject: Re: Mixing immediate assignment and delayed assignment === Subject: Re: ListPlot Joined/Filling bug? >When I try to generate the following plot: >ListPlot[{ >{15138, 15309, 15341, 15640, 16109, 16675, 16730, 16756, 16797, >17006, 17412, 17880, 18034, 18081, 18101, 18171, 18390, 18569, >18821, 18830}, >{45373, 45784, 46153, 47525, 48197, 50014, 50141, 50239, 50342, >50942, 51950, 52198, 52336, 52393, 52450, 52746, 53282, 53861, >54593, 54624}, >{52282, 52487, 52633, 53318, 53766, 57825, 58235, 58333, 58564, >59470, 60302, 61050, 61238, 61348, 61460, 61752, 62331, 63000, >63731, 63792}, >{11595, 11635, 11663, 11829, 11912, 12704, 12793, 12807, 12845, >13026, 13226, 13372, 13427, 13459, 13477, 13550, 13692, 13840, >14023, 14027}, >{67539, 68026, 68260, 69793, 70561, 77539, 77729, 77868, 78137, >80199, 81310, 81882, 82106, 82219, 82302, 82647, 83241, 83960, >84724, 84785} >}, Joined -> True] >I consistently hang Mathematica to the point where I have to restart >its kernel in order to restore functionality. Oddly, if Joined->True >is replaced with Filling->Axis, the problem persists, but if either >options is removed (so just the markers are plotted), the plot is >generated as expected. >Is anyone else seeing this behavior? >Any ideas what might be causing the problem? >I'm using 32-bit Mathematica 6.0.2.0 on Mac OS X 10.5. With: In[6]:= $Version Out[6]= 6.0 for Mac OS X PowerPC (32-bit) (June 19, 2007) running on 10.5.2, I have no problem simply pasting this into Mathematica and getting the expected result. So, my guess would be there is a problem with version 6.02 of Mathematica or a problem with your installation of Mathematica. === Subject: Funny behaviour of ClipboardNotebook[] (Q: How to copy programmatically?) When pasting quoted text from an e-mail, Mathematica will offer to remove the quoting marks. It says: The text you are pasting appears to be from a quoted email. Do you want Mathematica to remove the quoting marks before pasting it? (Yes|No) Here is a quoted expression to try this: > {9, > 0, > 7, > 8, > 7, > 2, > 5, > 0, > 7, > 1} The dialogue box also comes up when evaluating the following to access the clipboard programmatically: NotebookGet@ClipboardNotebook[] This is expected and understandable. But the dialogue box appears when using NotebookPut[] too if the clipboard contains a quoted expression! NotebookPut[Notebook[{abc}], ClipboardNotebook[]] Why does this happen? Is it a bug? Also, is this the correct way to *copy* a string to the clipboard programmatically? It does work, but I am not sure if Notebook[{abc}] (with no Cells) is a correct Notebook expression. (Where is the correct syntax documented?) === Subject: Possible values for the Method option for Graphics?? One of the very disappointing things about the documentation is that the possible values for certain options are very difficult to find. For example, take NIntegrate. The doc page mentions the Method option, but it does not say what the possible values are. Clicking the link just takes us to a generic information page for Method which doesn't even mention NIntegrate. It turns out that the values *are* documented at tutorial/NIntegrateOverview, but it is not at all obvious that one should look there. noticed that Graphics has a Method option too. What are the possible values and where are they documented? Szabolcs Horv.87t === Subject: Re: Possible values for the Method option for Graphics?? > One of the very disappointing things about the documentation is that the > possible values for certain options are very difficult to find. For example, take NIntegrate. The doc page mentions the Method option, > but it does not say what the possible values are. Clicking the link > just takes us to a generic information page for Method which doesn't > even mention NIntegrate. It turns out that the values *are* documented > at tutorial/NIntegrateOverview, but it is not at all obvious that one > should look there. noticed that Graphics has a Method option too. What are the possible > values and where are they documented? Szabolcs Horv=E1t One is CylinderPoints, which I believe is documented in Cylinder. Jason Merrill === Subject: Re: Possible values for the Method option for Graphics?? >> noticed that Graphics has a Method option too. What are the possible >> values and where are they documented? One is CylinderPoints, which I believe is documented in Cylinder. > There is also SpherePoints, and both of these are mentioned in the documentation for Graphics3D. But what are the possible values for Graphics (not Graphics3D)? === Subject: Re: Mathematica hangs... As you observe the last cell evaluation does not terminate in a reasonable time ~ 2 mins on my MacBook Pro running Leopard Syd Geraghty B.Sc, M.Sc. sydgeraghty@mac.com My System Mathematica 6.0.1 for Mac OS X x86 (64 - bit) (June 19, 2007) MacOS X V 10.5 .20 > Hello everyone, That's a bug report. I'm running v. 6.0.2 on a MacBook Pro under Leopard 10.5.2. I have a > notebook, nothing fancy, which hangs Mathematica when I execute it. As > a test, you can download this notebook from http://guerom00.free.fr/clutter/Notebook.zip It hangs at the last cell, when I want to plot the function, and I > have to quit the kernel. The same notebook runs perfectly on a MacPro under Tiger 10.4.11 so I > guess it is Leopard specific. Can anyone confirm the issue ? === Subject: Bug: AbsoluteOptions does not work with ViewMatrix The documentation states that With the setting ViewMatrix->Automatic, explicit forms for the matrix m can be found using AbsoluteOptions[g,ViewMatrix]. http://reference.wolfram.com/mathematica/ref/ViewMatrix.html However, AbsoluteOptions[Graphics3D[Cuboid[]], ViewMatrix] gives {ViewMatrix -> Automatic} This is the case even if the graphic has been rotated before using AbsoluteOptions. This is just one of the many graphics options in v6 which do not work with AbsoluteOptions. For many v6 options implementing AbsoluteOptions may be problematic, but I believe that ViewMatrix is not one of these, therefore this is a bug. === Subject: Strange behaviour of DialogInput and DialogCreate in 6.0.1 I am trying to use DialogInput to allow users of my notebook to set parameters in a nice graphical way. I'm running into a few problems and was hoping someone might point me in the right direction. The first problem is, if I set a variable using the result of DialogInput, I can't use that variable in subsequent commands in that cell. Below is a simple example (put contents in a single cell): In[1]:= test = 5 test = DialogInput[{Some Result, DefaultButton[DialogReturn[10]]}] Pause[1] Print[Hello] Pause[1] test Out[1]= 5 Out[1]= 10 Hello Out[5]= test I'm not sure I understand what's going on here. The final call of test appears to have *no* value, not even the original value 5 that was set. Now if we create a second cell, In[2]:= test Out[2]= 10 So it appears the variable does get set at some point, just not at the time I expect it to be set. The second problem I'm running into is that if I use a Dynamic around a global variable in a dialog, it will not update that variable when I exit from the dialog. In fact, one of the examples from the Help file doesn't work as advertised for me: In[1]:= CreateDialog[{TextCell[Enter a name: ], InputField[Dynamic[nm], String], DefaultButton[DialogReturn[ret = nm]]}]; In[1]:= ret Out[1]= ret Note that the history index is not incremented after the CreateDialog call. The third problem I have would probably be solved if I can get workarounds to the first two. That is, I want to make the dialog from DialogInput modal. I don't see how to do that. I would use CreateDialog or DialogNotebook, but as I mentioned, I don't appear to have any working mechanism to return values. Any suggestions of what I might be doing wrong or workarounds would be much appreciated. Januk === Subject: Writing variables in strings (opened from text files) Hello everyone, Can someone please help me with the following issue? I am importing a text file that I want to manipulate (replace some parts) and these parts shall be variables. Please help. I tried putting more commas for the variable but it didn't worked. I also tried with the ToString Here is a sample of what I want to do: game = Import[c:textfile.txt, Text]; w = 1500; game1 = StringReplace[gametheory, ( 3,) :> ( w,)]; game1 = StringReplace[gametheory1, ( 4,) :> ( w,)]; game1 = StringReplace[gametheory1, ( 5,) :> ( w,)]; game1 = StringReplace[gametheory1, ( 6,) :> ( w,)]; Export[c:textfile.txt, game1, Text]; === Subject: Re: Writing variables in strings (opened from text files) game = ToString[Table[RandomInteger[{1, 10}], {200}]]; and w = 1500; StringReplace[game, { 3, -> <> ToString[w] <> ,, 4, -> <> ToString[w] <> ,, 5, -> <> ToString[w] <> ,, 6, -> <> ToString[w] <> ,}] ?? > Hello everyone, Can someone please help me with the following issue? I am importing a > text file that I want to manipulate (replace some parts) and these > parts shall be variables. Please help. I tried putting more commas for > the variable but it didn't worked. I also tried with the ToString Here is a sample of what I want to do: game = Import[c:textfile.txt, Text]; w = 1500; game1 = StringReplace[gametheory, ( 3,) :> ( w,)]; > game1 = StringReplace[gametheory1, ( 4,) :> ( w,)]; > game1 = StringReplace[gametheory1, ( 5,) :> ( w,)]; > game1 = StringReplace[gametheory1, ( 6,) :> ( w,)]; Export[c:textfile.txt, game1, Text]; === Subject: Converting 3D graphics to 2D polygons In versions prior to 6 it was possible to convert 3D graphics to 2D like this: Graphics@Graphics3D[Cuboid[{0, 0, 0}]] // Show This does not work any more in v6. (Note that I am not trying to embed a 3D graphic into a 2D graphic, which can be done with Inset, but I would like to get the 2D projection of 3D points, lines and polygons.) Is there a way to do this in v6? One can use an ugly hack like ImportString@ExportString[Graphics3D[Cuboid[]], PDF] but this will break up all the polygons to many little pieces. === Subject: Re: Converting 3D graphics to 2D polygons > In versions prior to 6 it was possible to convert 3D graphics to 2D like > this: Graphics@Graphics3D[Cuboid[{0, 0, 0}]] // Show This does not work any more in v6. (Note that I am not trying to embed > a 3D graphic into a 2D graphic, which can be done with Inset, but I > would like to get the 2D projection of 3D points, lines and polygons.) Is there a way to do this in v6? One can use an ugly hack like > ImportString@ExportString[Graphics3D[Cuboid[]], PDF] > but this will break up all the polygons to many little pieces. This topic sounds interesting, and I've ever thought about something similar. Wish the following example be helpful :) GraphicsGrid[{MapIndexed[Function[{meshf, coord}, Plot3D[(Pi - (x^2 + y^2))/4, {x, -5, 5}, {y, -5, 5}, PlotRange -> All, PlotPoints -> 40, MeshFunctions -> meshf, Mesh -> 40, RegionFunction -> Function[{x, y, z}, 3 > Abs[(x - 1)^2 + y + ((3*z)/4)^2] > 1], PlotStyle -> None] /. Graphics3D[x_, y__] :> Graphics[x, AspectRatio -> Automatic] /. GraphicsComplex[x_, y_, z__] :> GraphicsComplex[(Drop[#1, coord] & ) /@ x, y]], {#1 & , #2 & , #3 & }]}] === Subject: 3D import/export format problems/bugs The following function gives errors with the DXF and 3DS formats in Mathematica 6.0.2: impexp[gr_Graphics3D, fmt_String] := ImportString[ExportString[gr, fmt], fmt] The graphic that gives errors is an example from the documentation: gr2 = Graphics3D[ Table[With[{p = {i, j, k}/5}, {RGBColor[p], Opacity[.75], Cuboid[p, p + .15]}], {i, 5}, {j, 5}, {k, 5}]] impexp[gr2,DXF] gives errors because of problems with ExportString[#, DXF] while impexp[gr2,3DS] generates an incorrect output. The reason why I was experimenting with the impexp[] function was that the PolygonIntersections option is not available any more in v6 (it is suggested to use options for Export instead), and I wanted to see how much of the formatting is preserved when 3D objects are transferred through different output formats. === Subject: Re: Viewpoint selector for Mac in 6.0? Ravi, 1) Make your plot. 2) Use the mouse to obtain the viewpoint that you want. 3) Right in front (on the left) of the plot output type 'Options[' and right after the plot (on the right) type ', Viewpoint'] and then evaluate. 4) That will give you the current Viewpoint option, which you could then copy into the plot Input specification. -- David Park djmpark@comcast.net http://home.comcast.net/~djmpark/ > Hello friends, It appears that the viewpoint selector for 3D graphics is absent in 6.0 > (Mac version). Is there an alternate way to manually choose a view > (other than trying different viewpoints repeatedly)? Suggestions > appreciated. Ravi > University of Washington > === Subject: Re: Viewpoint selector for Mac in 6.0? On Mar 22, 1:52 am, Ravi Balasubramanian (Mac version). Is there an alternate way to manually choose a view > (other than trying different viewpoints repeatedly)? Suggestions > appreciated. Ravi > University of Washington You can try this: Manipulate[ Module[{x, y, z}, x = r Sin[[Theta]] Cos[[Phi]]; y = r Sin[[Theta]] Sin[[Phi]]; z = r Cos[[Theta]]; Graphics3D[Cylinder[], ViewPoint -> {x, y, z}] ], ViewPoint, {{r, 3}, 1.5, 10, Appearance -> Labeled}, {{[Theta], Pi/4}, 0, Pi, Appearance -> Labeled}, {{[Phi], Pi/6}, -Pi, Pi, Appearance -> Labeled} ] === Subject: Re: Viewpoint selector for Mac in 6.0? > Hello friends, It appears that the viewpoint selector for 3D graphics is absent in 6.0 > (Mac version). Is there an alternate way to manually choose a view > (other than trying different viewpoints repeatedly)? Suggestions > appreciated. Here's a view point selector for you. I am not sure that I do the copying right, so corrections are welcome. Click the buttons to copy the values. viewPointSelector[gr_Graphics3D] := DynamicModule[ {vp = ViewPoint /. Options[Graphics3D], vv = ViewVertical /. Options[Graphics3D], va = ViewAngle /. Options[Graphics3D]}, Module[{copy}, copy[expr_] := NotebookPut[Notebook[{ToString[expr]}], ClipboardNotebook[]]; Panel[Column[ {Show[gr, ViewPoint -> Dynamic[vp], ViewVertical -> Dynamic[vv], ViewAngle -> Dynamic[va], SphericalRegion -> True, ImageSize -> 380], Grid[ {{Button[ViewPoint, copy[vp]], Dynamic[vp]}, {Button[ViewVertical, copy[vv]], Dynamic[vv]}, {Button[ViewAngle, copy[va]], Dynamic[va]}}, Alignment -> {Left, Baseline}]} ], ImageSize -> 400 ]]] (Side note: It would be nice if an automatically indented StandardForm expression would preserve the indentation levels exactly when copied.) === Subject: Re: Problem involving NDSolve I posted a solution to this problem on 12 March 08. -- David Park djmpark@comcast.net http://home.comcast.net/~djmpark/ > So here's my dilemma. I am trying to solve a differential equation with > complex roots. Mathematica is taking the incorrect root at certain points > when the function crosses over itself. I generated a set of all points at > which this occurs. The set is ProblemList={2.8, 5.599, 8.398} I now want to use these points in a function. My function is ComplexRoot[t_]:= If[Abs[t - ProblemList[[1]]] > .01 && Abs[t - > ProblemList[[2]]] > .01 && Abs[t - ProblemList[[ 3]]] > .01, > Evaluate[I*(2 + 1/2)(I*x[t])^(1 + 1/2)], Evaluate[p'[t - .01]]] The goal here is to have Mathematica take the correct root for all t other > than the problem t values, and at those t values simply continue in the > direction it was heading previously. So I want to then plug into the > differential equation solution=NDSolve[{x'[t] == 2p[t], x[0] == 0, p'[t]==ComplexRoot[t], p[0] > == 1}, > {x, p}, {t,0,10}, WorkingPrecision -> 30, MaxSteps -> Infinity][[1]]; and not get an error. Right now it gives me an error saying that I > haven't literally matched the independent variables. If it works, the following graph should have two loops and look like an > infinity sign with one of the loops being smaller than the other. ParametricPlot[{Re[p[t]] /. solution, Im[p[t]] /. solution}, > Evaluate[{t,0,10}],PlotRange -> {{-2, 2}, {-2, 2}}] What can I do to fix this issue? Any and all help is greatly appreciated. Alex > === Subject: Grabbing a value from a Dynamic Object Hi Folks, I am trying to use a series of control objects, specifically PopupMenus, so that the input to one PopupMenu will be used dynamically to provide the range of values for the subsequent PopupMenu. My area is not computer science, but I believe I get the idea that Dynamic is not evaluated in the kernal, but rather simply formatted in the front end of Mathematica. To extract a Dynamic value I have been attempting to use the command CurrentValue with no sucess. Here is my basic code: x = Null; y = Null; totgrades = PopupMenu[Dynamic[x], Range[12]] temp1 = CurrentValue[totgrades] gradesnow = PopupMenu[Dynamic[y], Range[temp1]] I keep getting the error message: Range::range: Range specification in Range[FrontEnd`CurrentValue[BoxData[3]]] does not have appropriate bounds. >> I understand that the Head of temp1 is NOT a number, but rather is a FrontEnd`CurrentValue.......so, how do I get a number that the second PopupMenu can actually use to produce a range of potential inputs from the user? I certainly appreciate any advice you might have! Mathematica is a wonderful piece of software, but there are times when it is truly frustating for a beginner. Todd _____ _ Never miss a thing. Make Yahoo your home page. http://www.yahoo.com/r/hs === Subject: Re: Grabbing a value from a Dynamic Object > Hi Folks, I am trying to use a series of control objects, > specifically PopupMenus, so that the input to one > PopupMenu will be used dynamically to provide the > range of values for the subsequent PopupMenu. My area is not computer science, but I believe I > get the idea that Dynamic is not evaluated in the > kernal, but rather simply formatted in the front end > of Mathematica. To extract a Dynamic value I have > been attempting to use the command CurrentValue with > no sucess. Here is my basic code: x = Null; y = Null; > totgrades = PopupMenu[Dynamic[x], Range[12]] > temp1 = CurrentValue[totgrades] > gradesnow = PopupMenu[Dynamic[y], Range[temp1]] > I keep getting the error message: Range::range: Range specification in > Range[FrontEnd`CurrentValue[BoxData[3]]] does not have > appropriate bounds. I understand that the Head of temp1 is NOT a number, > but rather is a FrontEnd`CurrentValue.......so, how do > I get a number that the second PopupMenu can actually > use to produce a range of potential inputs from the > user? I certainly appreciate any advice you might have! > Mathematica is a wonderful piece of software, but > there are times when it is truly frustating for a > beginner. Dynamic[x] is usually used for *displaying* (or sometimes setting) the value of x. x must not be wrapped in Dynamic when its value is used. Try this: PopupMenu[Dynamic[x], Range[12]] Dynamic@PopupMenu[Dynamic[y], Range[x]] === Subject: Re: Grabbing a value from a Dynamic Object I don't think you need CurrentValue. Try evaluating this example: PopupMenu[Dynamic[x], Range[12]] Dynamic[PopupMenu[Dynamic[y], Range[x]]] Is that what you want? > Hi Folks, I am trying to use a series of control objects, > specifically PopupMenus, so that the input to one > PopupMenu will be used dynamically to provide the > range of values for the subsequent PopupMenu. My area is not computer science, but I believe I > get the idea that Dynamic is not evaluated in the > kernal, but rather simply formatted in the front end > of Mathematica. To extract a Dynamic value I have > been attempting to use the command CurrentValue with > no sucess. Here is my basic code: x = Null; y = Null; > totgrades = PopupMenu[Dynamic[x], Range[12]] > temp1 = CurrentValue[totgrades] > gradesnow = PopupMenu[Dynamic[y], Range[temp1]] I keep getting the error message: Range::range: Range specification in > Range[FrontEnd`CurrentValue[BoxData[3]]] does not have > appropriate bounds. I understand that the Head of temp1 is NOT a number, > but rather is a FrontEnd`CurrentValue.......so, how do > I get a number that the second PopupMenu can actually > use to produce a range of potential inputs from the > user? I certainly appreciate any advice you might have! > Mathematica is a wonderful piece of software, but > there are times when it is truly frustating for a > beginner. Todd _____ _ > Never miss a thing. Make Yahoo your home page.http://www.yahoo.com/r/hs === Subject: Re: finding positions of elements in a list > I also tried Position but it wasn't clear to me if a pattern can be used for this. Hi. You have answers, but I see you were stuck on using Position. Here's one way if you ever need to use it: pts = {{20, 109}, {21, 50}, {20, 110}, {22, 60}}; Position[pts, {___, n_} /; n > 80] {{1}, {3}} Extract[pts, %] {{20, 109}, {20, 110}} -- HTH :>) Dana DeLouis > Hi. Having a few problems here with what I think should be a simple operation. I have a list as shown: mylist={{20, 109}, {20, 110}, {20, 111}, {21, 105}, {21, 106}, {21, 107},...} It's a list of {x,y} co-ordinates of some data points I'm analysing. I want to create a new list which contains only those data points whose y co-ordinate is greater than 80 ie. mylist[[n,2]]>80. Problem is, I can't work out how to use Select to do this when each element in the list has an x and a y co-ordinate. If I split the list into x and y co-ordinates and searched for those y values greater than 80, I would have a list of those y-values but would not know the corresponding x-values. I also tried Position but it wasn't clear to me if a pattern can be used for this. === Subject: Re: finding positions of elements in a list >> I also tried Position but it wasn't clear to me if a pattern can be used > for this. Hi. You have answers, but I see you were stuck on using Position. > Here's one way if you ever need to use it: > pts = {{20, 109}, {21, 50}, {20, 110}, {22, 60}}; Position[pts, {___, n_} /; n > 80] {{1}, {3}} Extract[pts, %] {{20, 109}, {20, 110}} There is one important caveat though, which is not present with Cases or Select. Position[] searches the expression at all levels. Suppose that we are trying to find those pairs whose second element is not 1. In[1]:= pts = RandomInteger[2, {10, 2}] Out[1]= {{1, 0}, {0, 0}, {2, 0}, {0, 2}, {2, 0}, {1, 2}, {2, 2}, {2, 1}, {1, 1}, {0, 1}} In[2]:= Position[pts, {___, n_} /; n =!= 1] Out[2]= {{1}, {2}, {3}, {4}, {5}, {6}, {7}, {}} Note the {} at the end of the list. It indicates that the complete expression matches too. There are many little details that can hide this behaviour for most input lists (e.g. using a different pattern or != instead of =!=), but it is good to mention that it is possible to only match against the elements of the list by using a level specification: Position[pts, {___, n_}, {1}] This might seem like a trivial detail, but I have been bitten by this type of mistake more than once. === Subject: SoundNote: velocity? Is there a way to set the velocity for the noteon midi message generated by SoundNote? I see there is an option for setting the volume of the note, but with midi volume and velocity are distinct concepts. Did that distinction get lost in Mathematica? === Subject: Re: Which function can do this? > Greeting all! > Now I need a function to transform a polynomial about x to the one > about x-1 > eg: x^3+2x^2+3x+4= (x-1)^3+5(x-1)^2+10(x-1)+10 > Does Mathematica supply a function to do this? -- > Best Wishes! > Yes. Normal[x^3 + 2*x^2 + 3*x + 4 + O[x, 1]^4] (x - 1)^3 + 5*(x - 1)^2 + 10*(x - 1) + 10 Andrzej Kozlowski === Subject: Which function can do this? Greeting all! Now I need a function to transform a polynomial about x to the one about x-1 eg: x^3+2x^2+3x+4= (x-1)^3+5(x-1)^2+10(x-1)+10 Does Mathematica supply a function to do this? -- Best Wishes! === Subject: Re: Which function can do this? Elements schrieb am 23.03.2008 07:02: > Greeting all! > Now I need a function to transform a polynomial about x to the one about x-1 > eg: x^3+2x^2+3x+4= (x-1)^3+5(x-1)^2+10(x-1)+10 > Does Mathematica supply a function to do this? > In[1]:= (x^3+2x^2+3x+4 /. x -> (y+1) // Simplify) /. y -> (x-1) Out[1]= 10 + 10*(-1 + x) + 5*(-1 + x)^2 + (-1 + x)^3 === Subject: Re: Which function can do this? Eliminate[{x^3 + 2 x^2 + 3 x + 4 == y, x - 1 == z}, x] /. z -> (x - 1) > Greeting all! > Now I need a function to transform a polynomial about x to the one about x-1 > eg: x^3+2x^2+3x+4= (x-1)^3+5(x-1)^2+10(x-1)+10 > Does Mathematica supply a function to do this? > === Subject: Drag and drop in the front end Enable drag and drop text editing can be checked on the Interface tab of preferences. (Apparently this feature has been available since version 3 but I did not know about it.) I think that this is useful (and it would be an order of magnitude more useful if it worked across applications [on Windows], e.g. for dragging code to the FE from a browser!), but it has some usability problems that even make it slightly dangerous: First, undo does not work with drag and drop. It removes the dropped object but it does not replace it to its original location (so the object is practically deleted). Second, when dragging something over a graphic, it completely replaces the graphic. Maybe it would be better to disallow dragging objects over graphics. === Subject: Counting nonzeros I want to count the # of NZ entries in an arbitrary multilevel list, say exp, that contains only integers. Is this the easiest way: k = Length[Flatten[exp]]-Count[Flatten[exp],0] === Subject: Re: Counting nonzeros > I want to count the # of NZ entries in an arbitrary multilevel list, > say exp, that contains only integers. Is this the easiest way: k = Length[Flatten[exp]]-Count[Flatten[exp],0] > Count[Flatten[exp],Except[0]] is a bit shorter Peter === Subject: Re: Counting nonzeros I want to count the # of NZ entries in an arbitrary multilevel list, > say exp, that contains only integers. Is this the easiest way: k = Length[Flatten[exp]]-Count[Flatten[exp],0] Count[Flatten[exp],Except[0]] is a bit shorter Peter try also: Count[exp,Except[0],-1] Robson === Subject: Re: Counting nonzeros > I want to count the # of NZ entries in an arbitrary multilevel list, > say exp, that contains only integers. Is this the easiest way: > k = Length[Flatten[exp]]-Count[Flatten[exp],0] >> Count[Flatten[exp],Except[0]] is a bit shorter >> Peter try also: Count[exp,Except[0],-1] Beware that as written the above example will count not only the non-zero integer value but also the number of intermediate structures that holds the values. To avoid that, one must use the second argument of Except, in this case setting it to the pattern _Integer. Count[exp, Except[0, _Integer], -1] The following computations should illustrate -- at least I hope! -- what is going on: In[1]:= exp = RandomInteger[{0, 1}, {3, 2, 2}] Out[1]= {{{1, 1}, {1, 1}}, {{1, 0}, {0, 0}}, {{1, 0}, {0, 0}}} In[2]:= Count[exp, Except[0], -1] Out[2]= 15 In[3]:= Count[exp, Except[0, _Integer], -1] Out[3]= 6 In[4]:= Count[Flatten[exp], Except[0]] Out[4]= 6 In[5]:= Level[exp, {-1}] % // Length Out[5]= {1, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0} Out[6]= 12 In[7]:= LeafCount@exp Out[7]= 22 In[8]:= Level[exp, {-1}, Heads -> True] % // Length Out[8]= {List, List, List, 1, 1, List, 1, 1, List, List, 1, 0, List, 0, 0, List, List, 1, 0, List, 0, 0} Out[9]= 22 -- === Subject: Re: Counting nonzeros > I want to count the # of NZ entries in an arbitrary multilevel list, > say exp, that contains only integers. Is this the easiest way: k = Length[Flatten[exp]]-Count[Flatten[exp],0] > In Mathematica 6 this: Total[Unitize[expr], Infinity] is both shorter and much faster. Andrzej Kozlowski === Subject: Re: Counting nonzeros > I want to count the # of NZ entries in an arbitrary multilevel list, > say exp, that contains only integers. Is this the easiest way: k = Length[Flatten[exp]]-Count[Flatten[exp],0] The easiest way might be in the eye of the beholder! What about the following? k = Total@Unitize@Flatten@exp (* Fastest Solution *) k = Count[exp, x_Integer /; x != 0, -1] (* Slower Solution *) The first expression uses Unitize to get a list of 0's and 1's only (every non zero entry is set to one). The second expression uses pattern matching and the third parameter of Count (setting level to -1 tells Mathematica to look for numbers, symbols and other objects that do not have subparts) to count the non zero entries. Here are the timings for each approach (we create some arbitrary integer data in the interval [-1, 1] first) In[1]:= exp = RandomInteger[{-1, 1}, {10, 10, 10}]; In[2]:= Timing@Total@Unitize@Flatten@exp Out[2]= {0.000083, 702} In[3]:= Timing@(Length[Flatten[exp]] - Count[Flatten[exp], 0]) Out[3]= {0.000172, 702} In[4]:= Timing@Count[exp, x_Integer /; x != 0, -1] Out[4]= {0.000736, 702} -- === Subject: Re: Counting nonzeros Using Count and Except[0] is surprisingly slow listi = RandomInteger[{0, 100}, 100000]; Length[listi] - Count[listi, 0] // Timing Out[30]= {0.02711, 98995} Count[listi, Except[0]] // Timing Out[31]= {0.063781, 98995} However, I remember reading in a previous post (which I cannot find) about Tally & Clip, perhaps by Carl Woll Tally[Clip[listi]][[1, 2]] // Timing Out[32]= {0.004693, 98995} I suppose there are even faster ways. Tom Dowling > I want to count the # of NZ entries in an arbitrary multilevel list, > say exp, that contains only integers. Is this the easiest way: k = Length[Flatten[exp]]-Count[Flatten[exp],0] === Subject: Re: Counting nonzeros > I want to count the # of NZ entries in an arbitrary multilevel list, > say exp, that contains only integers. Is this the easiest way: k = Length[Flatten[exp]]-Count[Flatten[exp],0] Suppose that we only have integers in the list. Count[expr, Except[0, _Integer], Infinity] Instead of _Integer, we could use _Symbol or _?AtomQ or some other pattern depending on the type of elements that need to be counted. (_Integer was necessary to avoid counting all the compound expressions, such as sublists.) === Subject: Re: Writing variables in strings (opened from text files) To use the value of the variable w rather than the character w use game1 = StringReplace[game, 3, :> ( <> ToString[w] <> ,)]; Check your use of the variable names gametheory and gametheory1 versus the variable names game and game1 Bob Hanlon > Hello everyone, Can someone please help me with the following issue? I am importing a > text file that I want to manipulate (replace some parts) and these > parts shall be variables. Please help. I tried putting more commas for > the variable but it didn't worked. I also tried with the ToString Here is a sample of what I want to do: game = Import[c:textfile.txt, Text]; w = 1500; game1 = StringReplace[gametheory, ( 3,) :> ( w,)]; > game1 = StringReplace[gametheory1, ( 4,) :> ( w,)]; > game1 = StringReplace[gametheory1, ( 5,) :> ( w,)]; > game1 = StringReplace[gametheory1, ( 6,) :> ( w,)]; Export[c:textfile.txt, game1, Text]; === Subject: Re: Saving Packages What use? Different ones, depending on the project. Basically my libraries (as I prefer to call them) contain everything from generic utilities valid for many projects, to project- specific function definitions, which are however too cumbersome to reside in the main notebook. It is simply the usual breaking down of big programs that I'm used to do since the days of plain old C programming. still ignorant about WHY packages exist at all - in a parallel world to the .nb world. And, more to the point, what would change for the outside user if Wolfram would provide a GetNB[] function, performing everything Get does - but for notebooks? wondering... alessandro Jerry ha scritto: > but didnt find so much info - I'll have to dig deeper. Your answers were of course right: setting the cells as init cells did > the right thing. Yet I'd like to explain better what is my larger problem is: > to break down a big project in pieces, it is correct then to save big > chunks of code definitions as packages? > I'm asking because I'd like to still keep on modifying those packages, > as in a standard notebook. But opening the .m file brings up a > different interface, which although it seems useful (drop down boxes > with Functions and Sections - I'd like to have them in the notebook!) > it's not so clear to me if I'm losing something present in the > notebook interface. file, modify it as needed, select all cells and set them to init, and > save as .m file. Correct? Sir, I am very curious: what would you then do with the .m > file? > What use does it have? === Subject: Re: Saving Packages the packages exist for the same reason why your MS-Word has macros/VBasic and you can write letters, and other short text documents with it. The notebooks are text documents with embedded code for teaching/talks .. and the code is typical something that you do *once* and the packages include the code for something that you wish to do on and on. > What use? Different ones, depending on the project. > Basically my libraries (as I prefer to call them) contain > everything from generic utilities valid for many projects, to project- > specific function definitions, which are however too cumbersome to > reside in the main notebook. It is simply the usual breaking down of > big programs that I'm used to do since the days of plain old C > programming. still ignorant about WHY packages exist at all - in a parallel world > to the .nb world. > And, more to the point, what would change for the outside user if > Wolfram would provide a GetNB[] function, performing everything Get > does - but for notebooks? wondering... > alessandro Jerry ha scritto: but didnt find so much info - I'll have to dig deeper. Your answers were of course right: setting the cells as init cells did > the right thing. Yet I'd like to explain better what is my larger problem is: > to break down a big project in pieces, it is correct then to save big > chunks of code definitions as packages? > I'm asking because I'd like to still keep on modifying those packages, > as in a standard notebook. But opening the .m file brings up a > different interface, which although it seems useful (drop down boxes > with Functions and Sections - I'd like to have them in the notebook!) > it's not so clear to me if I'm losing something present in the > notebook interface. file, modify it as needed, select all cells and set them to init, and > save as .m file. Correct? > Sir, I am very curious: what would you then do with the .m >> file? >> What use does it have? > === Subject: Re: Saving Packages > but didnt find so much info - I'll have to dig deeper. Your answers were of course right: setting the cells as init cells did > the right thing. Yet I'd like to explain better what is my larger problem is: > to break down a big project in pieces, it is correct then to save big > chunks of code definitions as packages? > I'm asking because I'd like to still keep on modifying those packages, > as in a standard notebook. But opening the .m file brings up a > different interface, which although it seems useful (drop down boxes > with Functions and Sections - I'd like to have them in the notebook!) > it's not so clear to me if I'm losing something present in the > notebook interface. file, modify it as needed, select all cells and set them to init, and > save as .m file. Correct? > Sir, I am very curious: what would you then do with the .m file? What use does it have? === Subject: Re: Saving Packages > Yet I'd like to explain better what is my larger problem is: > to break down a big project in pieces, it is correct then to save big > chunks of code definitions as packages? Absolutely, that is much better than handle many notebooks which you have to evaluate before starting to work... > I'm asking because I'd like to still keep on modifying those packages, > as in a standard notebook. But opening the .m file brings up a > different interface, which although it seems useful (drop down boxes > with Functions and Sections - I'd like to have them in the notebook!) > it's not so clear to me if I'm losing something present in the > notebook interface. well, what you see in fact is a notebook - with a special style which is trimmed to work on mathematica code and some extras which make possible to save the noncode parts of the notebook within the .m file, too. The main drawback I see is that at this time not too much (none?) information is available wheter and how you can customize this style with an own stylesheet. > file, modify it as needed, select all cells and set them to init, and > save as .m file. Correct? Basically yes, but if you set the Notebooks option AutoSavePackage to Automatic, then the .m file will be generated automatically each time you save the notebook, which makes the whole process very handy. As has been pointed out this is the recommended way to go for versions < 6, for version 6 the recommended way seems to be to edit .m files directly, but the old way still works. It's a matter of taste which way you go. hth, albert === Subject: Re: finding positions of elements in a list > I also tried Position but it wasn't clear to me if a pattern can be = used >> for this. >> Hi. You have answers, but I see you were stuck on using Position. >> Here's one way if you ever need to use it: >> pts = {{20, 109}, {21, 50}, {20, 110}, {22, 60}}; >> Position[pts, {___, n_} /; n > 80] >> {{1}, {3}} >> Extract[pts, %] >> {{20, 109}, {20, 110}} There is one important caveat though, which is not present with Cases = or > Select. Position[] searches the expression at all levels. Suppose = that > we are trying to find those pairs whose second element is not 1. In[1]:= pts = RandomInteger[2, {10, 2}] > Out[1]= {{1, 0}, {0, 0}, {2, 0}, {0, 2}, {2, 0}, {1, 2}, {2, 2}, > {2, 1}, {1, 1}, {0, 1}} In[2]:= Position[pts, {___, n_} /; n =!= 1] > Out[2]= {{1}, {2}, {3}, {4}, {5}, {6}, {7}, {}} Note the {} at the end of the list. It indicates that the complete > expression matches too. There are many little details that can hide this behaviour for most > input lists (e.g. using a different pattern or != instead of = =!=), but > it is good to mention that it is possible to only match against the > elements of the list by using a level specification: Position[pts, {___, n_}, {1}] This might seem like a trivial detail, but I have been bitten by this > type of mistake more than once. Yes. Good point. As another example, to avoid errors with the following method, one should set Heads -> False. pts = {{20, 109}, {21, 50}, {20, 110}, {22, 60}}; Position[pts, v_ /; Last[v] > 80, 1, Heads -> False] {{1}, {3}} Extract[pts, %] {{20, 109}, {20, 110}} === Subject: Match Pairs of Numbers Any help would be appreciated. I am using Mathematica 5.2 & 6.0 I am having trouble finding the correct form of Pattern Matching for pairs of Numbers. I do not know whether to use Select, Cases, Pick, etc. I am also unsure how to set the pattern matching argument. Assume I have the list lst = {{1,1}, {1,2}, {1,3}, {1,4}, {2,2}, {3,1}, {3,2}, {3,3}, {4,1}, {4,4}} I would like to match/select pairs that have the same set of numbers only reversed, that is, the selection would find {{1,3}, {3,1}, {1,4}, {4,1} } Andrew C Beveridge MS M888 Los Alamos National Laboratory Los Alamos, NM 87545 505-665-2092 e-mail: acbev@lanl.gov === Subject: Re: Match Pairs of Numbers > Any help would be appreciated. I am using Mathematica 5.2 & 6.0 I am having trouble finding the correct form of Pattern Matching for > pairs of Numbers. I do not know whether to use Select, Cases, Pick, > etc. I am also unsure how to set the pattern matching argument. Assume I have the list lst = {{1,1}, {1,2}, {1,3}, {1,4}, {2,2}, {3,1}, {3,2}, {3,3}, {4,1}, {4,4}} > I would like to match/select pairs that have the same set of numbers > only reversed, that is, the selection would find {{1,3}, {3,1}, {1,4}, {4,1} } > Intersection[lst, Reverse /@ lst] Select[%, UnsameQ @@ # &] === Subject: Re: Match Pairs of Numbers > Any help would be appreciated. I am using Mathematica 5.2 & 6.0 I am having trouble finding the correct form of Pattern Matching for > pairs of Numbers. I do not know whether to use Select, Cases, Pick, > etc. I am also unsure how to set the pattern matching argument. Assume I have the list lst = {{1,1}, {1,2}, {1,3}, {1,4}, {2,2}, {3,1}, {3,2}, {3,3}, > {4,1}, {4,4}} > I would like to match/select pairs that have the same set of numbers > only reversed, that is, the selection would find {{1,3}, {3,1}, {1,4}, {4,1} } Andrew C Beveridge > MS M888 > Los Alamos National Laboratory > Los Alamos, NM 87545 505-665-2092 > e-mail: acbev@lanl.gov > Here is an algo-rhythmic newbie approach :) > In[2]:= > Last[Reap[While[ > Length[lst] >= 1, > i = Random[Integer, > {1, Length[lst]}]; > c = lst[[i]]; > rc = Reverse[c]; > If[Length[Position[lst, > rc]] > 0 && > c != rc, > Sow[{c, rc}]; , Null]; > lst = Delete[lst, > Position[lst, rc]]; > lst = Delete[lst, > Position[lst, c]]; ]]] > Out[2]= > {{{{4, 1}, {1, 4}}, > {{3, 1}, {1, 3}}}} J=E1nos ---------------------------------------------- Trying to argue with a politician is like lifting up the head of a corpse. (S. Lem: His Master Voice) === Subject: Re: Match Pairs of Numbers The following will hopefully do what you want, though the resulting list isn't sorted into the pairs: lst = {{1, 1}, {1, 2}, {1, 3}, {1, 4}, {2, 2}, {3, 1}, {3, 2}, {3, 3}, {4, 1}, {4, 4}}; In[4]:= Select[ Intersection[lst, Reverse /@ lst], #1[[1]] != #1[[2]] & ] Out[4]= {{1, 3}, {1, 4}, {3, 1}, {4, 1}} This forms the intersection of the list of pairs and the reversed pairs (keeping only those elements which are present both forwards and backwards), and then Select chooses those elements which don't have both numbers the same in each pair (e.g. {1,1} leaves, as does {2,2}, etc.). C.O. > Any help would be appreciated. I am using Mathematica 5.2 & 6.0 I am having trouble finding the correct form of Pattern Matching for > pairs of Numbers. I do not know whether to use Select, Cases, Pick, > etc. I am also unsure how to set the pattern matching argument. Assume I have the list lst = {{1,1}, {1,2}, {1,3}, {1,4}, {2,2}, {3,1}, {3,2}, {3,3}, {4,1}, > {4,4}} > I would like to match/select pairs that have the same set of numbers > only reversed, that is, the selection would find {{1,3}, {3,1}, {1,4}, {4,1} } Andrew C Beveridge > MS M888 > Los Alamos National Laboratory > Los Alamos, NM 87545 505-665-2092 > e-mail: acbev@lanl.gov -- Curtis Osterhoudt cfo@remove_this.lanl.and_this.gov PGP Key ID: 0x4DCA2A10 Please avoid sending me Word or PowerPoint attachments See http://www.gnu.org/philosophy/no-word-attachments.html === Subject: Re: Match Pairs of Numbers > I am having trouble finding the correct form of Pattern Matching for > pairs of Numbers. I do not know whether to use Select, Cases, Pick, > etc. I am also unsure how to set the pattern matching argument. Assume I have the list lst = {{1,1}, {1,2}, {1,3}, {1,4}, {2,2}, {3,1}, {3,2}, {3,3}, {4,1}, {4,4}} > I would like to match/select pairs that have the same set of numbers > only reversed, that is, the selection would find {{1,3}, {3,1}, {1,4}, {4,1} } The following examples should help you started. Note that they have not been optimized for speed, though the recursive example (myComp) is much faster than the first one (which try to illustrate how to use Pick). Also, note that the best strategy to solve the problem depends on many factors you did not mention, such as the size of the list, possibility of many occurrences of matching pairs (say, several {1,4}'s), whether the order of the matching pairs returned in the solution is important, etc. lst = {{1,1},{1,2},{1,3},{1,4},{2,2},{3,1},{3,2},{3,3},{4,1},{4,4}}; myCheck[lst_List] := Module[{rev = Reverse /@ lst}, Flatten[Table[ Pick[lst, MapThread[SameQ, {lst, RotateLeft[rev, n]}]], {n, Length@lst - 1}] /. {} -> Sequence[], 1]] myCheck[lst] (* ==> {{1, 3}, {1, 4}, {4, 1}, {3, 1}} *) myComp[data_List] := Module[{mySearch}, mySearch[pair_List, lst_List /; Length[lst] > 0] := Union[Cases[Reverse /@ lst, pair], mySearch[First@lst, Rest@lst]]; mySearch[pair_List, lst_List] := {}; Block[{$RecursionLimit = 10 + Length@data}, mySearch[First@lst, Rest@lst] ] ] myComp[lst] (* ==> {{1, 3}, {1, 4}} *) -- === Subject: Re: ListPlot Joined/Filling bug? Alexander ha escrito: > When I try to generate the following plot: ListPlot[{ {15138, 15309, 15341, 15640, 16109, 16675, 16730, 16756, 16797, > 17006, 17412, 17880, 18034, 18081, 18101, 18171, 18390, 18569, > 18821, 18830}, {45373, 45784, 46153, 47525, 48197, 50014, 50141, 50239, 50342, > 50942, 51950, 52198, 52336, 52393, 52450, 52746, 53282, 53861, > 54593, 54624}, {52282, 52487, 52633, 53318, 53766, 57825, 58235, 58333, 58564, > 59470, 60302, 61050, 61238, 61348, 61460, 61752, 62331, 63000, > 63731, 63792}, {11595, 11635, 11663, 11829, 11912, 12704, 12793, 12807, 12845, > 13026, 13226, 13372, 13427, 13459, 13477, 13550, 13692, 13840, > 14023, 14027}, {67539, 68026, 68260, 69793, 70561, 77539, 77729, 77868, 78137, > 80199, 81310, 81882, 82106, 82219, 82302, 82647, 83241, 83960, > 84724, 84785} }, Joined -> True] I consistently hang Mathematica to the point where I have to restart > its kernel in order to restore functionality. Oddly, if Joined->True > is replaced with Filling->Axis, the problem persists, but if either > options is removed (so just the markers are plotted), the plot is > generated as expected. Is anyone else seeing this behavior? I can reproduce the behavior in a simpler example. In[1]:= $Version Out[1]= 6.0 for Mac OS X x86 (64-bit) (February 7, 2008) In[2]:= myList = {15138, 15309, 15341, 15640, 16109}; In[3]:= ListPlot[myList] Works as expected. However, both ListPlot[myList, Joined -> True] and ListLinePlot[myList] hang Mathematica. This does not happen if myList has only 4 points. Looks like a bug related to the size of the numbers. Everything works fine with myList/100. Juli=E1n === Subject: Re: ListPlot Joined/Filling bug? > Alexander ha escrito: >> When I try to generate the following plot: >> ListPlot[{ >> {15138, 15309, 15341, 15640, 16109, 16675, 16730, 16756, 16797, >> 17006, 17412, 17880, 18034, 18081, 18101, 18171, 18390, 18569, >> 18821, 18830}, >> {45373, 45784, 46153, 47525, 48197, 50014, 50141, 50239, 50342, >> 50942, 51950, 52198, 52336, 52393, 52450, 52746, 53282, 53861, >> 54593, 54624}, >> {52282, 52487, 52633, 53318, 53766, 57825, 58235, 58333, 58564, >> 59470, 60302, 61050, 61238, 61348, 61460, 61752, 62331, 63000, >> 63731, 63792}, >> {11595, 11635, 11663, 11829, 11912, 12704, 12793, 12807, 12845, >> 13026, 13226, 13372, 13427, 13459, 13477, 13550, 13692, 13840, >> 14023, 14027}, >> {67539, 68026, 68260, 69793, 70561, 77539, 77729, 77868, 78137, >> 80199, 81310, 81882, 82106, 82219, 82302, 82647, 83241, 83960, >> 84724, 84785} >> }, Joined -> True] >> I consistently hang Mathematica to the point where I have to restart >> its kernel in order to restore functionality. Oddly, if Joined->True >> is replaced with Filling->Axis, the problem persists, but if either >> options is removed (so just the markers are plotted), the plot is >> generated as expected. >> Is anyone else seeing this behavior? I can reproduce the behavior in a simpler example. In[1]:= $Version Out[1]= 6.0 for Mac OS X x86 (64-bit) (February 7, 2008) In[2]:= myList = {15138, 15309, 15341, 15640, 16109}; In[3]:= ListPlot[myList] Works as expected. However, both ListPlot[myList, Joined -> True] and ListLinePlot[myList] hang Mathematica. This does not happen if myList has only 4 points. > Looks like a bug related to the size of the numbers. Everything works > fine with myList/100. For what is worth, I can reproduce the bug on the folloiwng system : v6.0.2 on a Mac (Mac OS X 10.5.2) Intel (64-bit); but not on this one : v6.0.2 on a PC (Windows XP SP2) Intel (32-bit). I have used the large list and the shorter one (5 elements) and the variations of the plot command. -- === Subject: Re: ListPlot Joined/Filling bug? For $Version on my PC, I get: 6.0 for Microsoft Windows (32-bit) (February 7, 2008) which is for version 6.0.2.0 using WinXP Pro with SP2. I ran ALL three variations you mentioned with no problems. If you'd like, I'll send you my Notebook file with its output included. Benjamin Tubb brtubb@pdmusic.org > When I try to generate the following plot: ListPlot[{ {15138, 15309, 15341, 15640, 16109, 16675, 16730, 16756, 16797, > 17006, 17412, 17880, 18034, 18081, 18101, 18171, 18390, 18569, > 18821, 18830}, {45373, 45784, 46153, 47525, 48197, 50014, 50141, 50239, 50342, > 50942, 51950, 52198, 52336, 52393, 52450, 52746, 53282, 53861, > 54593, 54624}, {52282, 52487, 52633, 53318, 53766, 57825, 58235, 58333, 58564, > 59470, 60302, 61050, 61238, 61348, 61460, 61752, 62331, 63000, > 63731, 63792}, {11595, 11635, 11663, 11829, 11912, 12704, 12793, 12807, 12845, > 13026, 13226, 13372, 13427, 13459, 13477, 13550, 13692, 13840, > 14023, 14027}, {67539, 68026, 68260, 69793, 70561, 77539, 77729, 77868, 78137, > 80199, 81310, 81882, 82106, 82219, 82302, 82647, 83241, 83960, > 84724, 84785} }, Joined -> True] I consistently hang Mathematica to the point where I have to restart > its kernel in order to restore functionality. Oddly, if Joined->True > is replaced with Filling->Axis, the problem persists, but if either > options is removed (so just the markers are plotted), the plot is > generated as expected. Is anyone else seeing this behavior? Any ideas what might be causing the problem? I'm using 32-bit Mathematica 6.0.2.0 on Mac OS X 10.5. === Subject: Basic plotting of an evaluated function I am trying to do something basic--but I cannot figure it out I have some function in two varaibles f[x_,y_]= some arbitrary polynomial Now I want to minimize the function with respect to y over some compact interval with fixed x NMinimize[{f[x,y],y=995,y=989},y] I want to plot the y's versus the x's. I have tried many things like defining s[x_]=Part[NMinimize[{f[x,y],y=995,y=989},y],2] Plot[s[x],{x,-14, 46}] or variations Plot[tt/.s[x],{x,-14, 46}]. Many error messages or nothing at all results......... I am sure this is easy, and someone can suggest how to do this. However, one more thing would be greatly helpful (give a man a decent and readable Mathematica manual and he can feed himself...) I am baffled by what Mathematica wants when it comes to using a single part of a list and changing it to a scalar. Suppose as above q is a vector with a rule assigning a value to some variable x that is x- >some number, and this assignment is in the third position of the list What is going on with q/.d[[3]] for example: Is q now a scalar? If not why not? === Subject: Re: Basic plotting of an evaluated function it would be helpful a) if you would consider to read the manual b) use correct Mathematica syntax because NMinimize[{f[x,y],y=995,y=989},y] is remarkable nonsense anyway f[x_?NumericQ, y_?NumericQ] := x*(990 - y^2) s[x_?NumericQ] := y /. Last[NMinimize[{f[x, y], y < 995, y > 989}, y]] Plot[s[x], {x, -14, 46}] > I am trying to do something basic--but I cannot figure it out > I have some function in two varaibles f[x_,y_]= some arbitrary polynomial Now I want to minimize the function with respect to y over some > compact interval with fixed x NMinimize[{f[x,y],y=995,y=989},y] I want to plot the y's versus the x's. I have tried many things like defining s[x_]=Part[NMinimize[{f[x,y],y=995,y=989},y],2] Plot[s[x],{x,-14, 46}] or variations Plot[tt/.s[x],{x,-14, 46}]. Many error messages or nothing at all results......... I am sure this is easy, and someone can suggest how to do this. However, one more thing would be greatly helpful (give a man a decent > and readable Mathematica manual and he can feed himself...) I am baffled by what Mathematica wants when it comes to using a single > part of a list and changing it to a scalar. Suppose as above q is a > vector with a rule assigning a value to some variable x that is x- >> some number, and this assignment is in the third position of the list What is going on with q/.d[[3]] for example: Is q now a scalar? If > not why not? === Subject: Re: Basic plotting of an evaluated function > I have some function in two varaibles f[x_,y_]= some arbitrary polynomial Now I want to minimize the function with respect to y over some > compact interval with fixed x NMinimize[{f[x,y],y=995,y=989},y] There are two syntax errors in the above line: First, the expression y = 995 _assigns_ the integer value 995 to the symbol y. What you had in mind was the comparison operator for equality, which is written as a double equal sign == in Mathematica. (See Set, =, Second, NMinimize accepts constraints expressed in the form of inequalities and domain specification. Therefore, your expression should read, Minimize[{f[x, y], 989 <= y <= 995}, y] > I want to plot the y's versus the x's. I have tried many things like defining s[x_]=Part[NMinimize[{f[x,y],y=995,y=989},y],2] Using SetDelayed, :=, and the replacement operator /. should work here. s[x_] := y /. Last@NMinimize[{f[x, y], 989 <= y <= 995}, y] > Plot[s[x],{x,-14, 46}] The following expressions are a working example of what you are looking for. f[x_, y_] := x^2 - 3 y^2 + x y + 10 s[x_] := y /. Last@NMinimize[{f[x, y], 989 <= y <= 995}, y] Plot[s[x], {x, -14, 46}] Hope this helps, -- === Subject: Color Options for PlanarGraphPlot I am interested in applying color options to PlanarGraphPlot. Under Options[PlanarGraphPlot] there is listed the option ColorOutput -> Automatic. Anyone know how to use this option? I have had no luck. Here is some sample data: sampledata = {{0.854, 0.885}, {1.827, 4.126}, {4.255, 2.872}, {0.888, 4.872}, {4.507, 0.721}, {2.978, 1.998}, {3.507, 4.534}} The best I have been able to do is to apply a color directive to the Line primitive- it works but the approach not very pleasing. PlanarGraphPlot[sampledata, Frame -> True, TextStyle -> {FontSize -> 14, FontColor -> Blue}] /. Line[x_] -> {Red, Line[x]} Note: using the option BaseStyle->Red makes everything in the plot Red. Of course, one could undo some of the BaseStyle by then applying LabelStyle, FrameStyle etc as shown below PlanarGraphPlot[bin, Frame -> True, BaseStyle -> {Red, FontSize -> 14}, LabelStyle -> {Black, FontSize -> 12}, FrameStyle -> Black] Brian ps TextStyle is no longer listed as an option but still appears to work === Subject: Re: Color Options for PlanarGraphPlot the ColorOutput option is for B/W or color printers. If you prepare a book and want to use pictures generated by Mathematica than your publisher is not always happy with color images and you need Black/White pictures when the final PostScript or PDF is created. For this run of your Mathematica input, you should set ColorOutput. But As of Version 6.0, ColorOutput has been superseded by ColorFunction, ColorData and related functions. > I am interested in applying color options to PlanarGraphPlot. Under > Options[PlanarGraphPlot] there is listed the option ColorOutput - Automatic. Anyone know how to use this option? I have had no luck. > Here is some sample data: sampledata = {{0.854, 0.885}, {1.827, 4.126}, {4.255, 2.872}, {0.888, > 4.872}, {4.507, 0.721}, {2.978, 1.998}, {3.507, 4.534}} The best I have been able to do is to apply a color directive to the > Line primitive- it works but the approach not very pleasing. PlanarGraphPlot[sampledata, Frame -> True, > TextStyle -> {FontSize -> 14, FontColor -> Blue}] /. Line[x_] - {Red, Line[x]} Note: using the option BaseStyle->Red makes everything in the plot > Red. Of course, one could undo some of the BaseStyle by then > applying LabelStyle, FrameStyle etc as shown below PlanarGraphPlot[bin, Frame -> True, > BaseStyle -> {Red, FontSize -> 14}, > LabelStyle -> {Black, FontSize -> 12}, FrameStyle -> Black] Brian ps TextStyle is no longer listed as an option but still appears to work > === Subject: Re: Color Options for PlanarGraphPlot the ColorOutput option is for B/W or color printers. > If you prepare a book and want to use pictures generated > by Mathematica than your publisher is not always happy with > color images and you need Black/White pictures when the final > PostScript or PDF is created. For this run of your Mathematica > input, you should set ColorOutput. But > As of Version 6.0, ColorOutput has been superseded by ColorFunction, > ColorData and related functions. I wonder why ColorOutput was removed. ColorFunction is used /before/ generating the graphic. ColorOutput could be used to convert to GrayLevel after it has been generated, making it easy to create several versions of the graphic without additional software. But it is true that in v 5.2 ColorOutput -> CMYKColor was far from precise ... Just try Plot3D[Sin[x y], {x, 0, 3}, {y, 0, 3}] Show[%, ColorOutput -> CMYKColor] === Subject: Re: Bug: symbol recreates itself suddenly There are some things that are not forbidden by the manual, but still, doing them might be a bad idea. For example, making definitions such as the following isn't a good idea: Sign[x]^=1; Instead one should use the assumptions mechanism: $Assumptions = Re[x] > 0 && Im[x] == 0; I agree that the documentation could be improved for such cases. Bhuvanesh, Wolfram Research === Subject: Re: choose elements from list based on elements in different list > I'm trying to choose elements from list based on elements in different > list and I came up with the ideas listed below. It seems to me that > there are a few too many steps involved here, and I need to run this on > larger lists (~20000 entries). > Are there ways to improve this? > Claus Here is the mathematica code: Reihe1={22,33,44,0,0,16,5,0,0,0} > Reihe2={16,27,0,0,5,11,5,0,0,12} {22, 33, 44, 0, 0, 16, 5, 0, 0, 0} {16, 27, 0, 0, 5, 11, 5, 0, 0, 12} (*Find out where in Reihe1 and in Reihe2 are Zeros and notZeros*) Reihe1Is0 = Thread[Reihe1 == 0] > Reihe1Not0 = Thread[Reihe1 != 0] > Reihe2Is0 = Thread[Reihe2 == 0] > Reihe2Not0 = Thread[Reihe2 != 0] {False, False, False, True, True, False, False, True, True, True} {True, True, True, False, False, True, True, False, False, False} {False, False, True, True, False, False, False, True, True, False} {True, True, False, False, True, True, True, False, False, True} (*Select the values of Reihe1 and Reihe2 which are of interest There are 4 Cases (not all of them calculated later) : > Case1 : Reihe1 and Reihe2 are 0 > Case2 : Reihe1 and Reihe2 are NOT 0 > Case3 : (Reihe2 is NOT 0) AND (Reihe1 is 0) > Case4 : (Reihe1 is NOT 0) AND (Reihe2 is 0)*) PreCase3=Pick[Reihe2,Reihe1Is0] > PreCase4=Pick[Reihe1,Reihe2Is0] {0, 5, 0, 0, 12} {44, 0, 0, 0} Case3=Select[PreCase3,#>0&] > Case4=Select[PreCase4,#>0&] {5, 12} {44} Hi. Just another option would be to combine the two lists into an integer.(0,1,2,or 3) Reihe1 = {22, 33, 44, 0, 0, 16, 5, 0, 0, 0}; Reihe2 = {16, 27, 0, 0, 5, 11, 5, 0, 0, 12}; ptn = 2*DiscreteDelta /@ Reihe1 + DiscreteDelta /@ Reihe2 {0, 0, 1, 3, 2, 0, 0, 3, 3, 2} Pick[Reihe2, ptn, 2] {5, 12} Pick[Reihe1, ptn, 1] {44} -- HTH :>) Dana DeLouis Mathematica 6 But reading 5.2 Help. :>( === Subject: Re: Counting nonzeros >I want to count the # of NZ entries in an arbitrary multilevel list, >say exp, that contains only integers. Is this the easiest way: >k = Length[Flatten[exp]]-Count[Flatten[exp],0] There are a number of ways to do what you want. I think using Unitize to convert the non-zero entries to 1 and then summing using Total is likely to be the fastest, i.e., Total[Flatten@Unitize@exp] or Total[Total@Unitize@exp] === Subject: Tally I'm trying the following: *Dlist = {{{0,1},{0,1}},{{1,0},{1,0}},{{1,0},{0,1}},{{0,1},{1,0}}};* The output is: *{{{{0,1},{0,1}},1},{{{1,0},{1,0}},1},{{{1,0},{0,1}},2}}* instead of *{{{{0,1},{0,1}},2},{{{1,0},{0,1}},2}}* If I remove the last member from DList *Dlist = {{{0,1},{0,1}},{{1,0},{1,0}},{{1,0},{0,1}}};* then I got a correct answer *{{{{0,1},{0,1}},2},{{{1,0},{0,1}},1}}.* Is anything wrong with my original code? Armen === Subject: Re: Tally > I'm trying the following: > *Dlist = {{{0,1},{0,1}},{{1,0},{1,0}},{{1,0},{0,1}},{{0,1},{1,0}}};* > The output is: *{{{{0,1},{0,1}},1},{{{1,0},{1,0}},1},{{{1,0},{0,1}},2}}* instead of *{{{{0,1},{0,1}},2},{{{1,0},{0,1}},2}}* If I remove the last member from DList *Dlist = {{{0,1},{0,1}},{{1,0},{1,0}},{{1,0},{0,1}}};* then I got a correct answer *{{{{0,1},{0,1}},2},{{{1,0},{0,1}},1}}.* Here is solution to this issue, by writing our own Tally function. Note that code of the function myTally is only one possibility among many and that there has been no attempt to optimize it for speed (though it takes about half a second to process 100,000 pairs of pairs). We assume that the matrix entries are only 0 or 1 (_Integer). The idea is, therefore, to look at en entry of the form {{a, b}, {c, d}} (where a, b, c, and d are in {0, 1}) as if it were, having flatten the matrix, a binary representation of a decimal number. For instance, say we have the entry {{0, 1}, {0, 1)}. We look at it as if it were 0101 (binary), i.e. 5 in decimal. Also, we check the reverse representation of the entry (that is {{b, a}, {d, c}}) and take the minimum value of both representation as the canonical form for this equivalent entries. In our example, the reverse entry of {{0, 1}, {0, 1)} is {{1, 0}, {1, 0)}, that is 1010 in binary or 10 in decimal. So both entries {{0, 1}, {0, 1)} and {{1, 0}, {1, 0)} are going to be encoded as 5 in the code below. When the whole list is processed, Tally is applied, and finally we decode the decimal entries into their pair of pairs equivalent. Well, I hope this makes sense! Here is the code for myTally, followed by some tests. In[1]:= myTally[lst_List] := Module[{l1, l2, l3, l4}, l3 = Min /@ Transpose[{l1, l2}]; l1 =.; l2 =.; l4 = {PadLeft[IntegerDigits[First@#, 2], 4], Last@#} & /@ Tally@l3; l3 =.; {Partition[First@#, 2], Last@#} & /@ l4 ] In[2]:= Dlist = {{{0, 1}, {0, 1}}, {{1, 0}, {1, 0}}, {{1, 0}, {0, 1}}, {{0, 1}, {1, 0}}}; myTally[Dlist] Out[3]= {{{{0, 1}, {0, 1}}, 2}, {{{0, 1}, {1, 0}}, 2}} In[4]:= Dlist = RandomInteger[{0, 1}, {10, 2, 2}] myTally[Dlist] Out[4]= {{{0, 0}, {1, 1}}, {{0, 1}, {1, 0}}, {{0, 1}, {0, 0}}, {{0, 0}, {0, 0}}, {{0, 1}, {1, 1}}, {{1, 0}, {0, 1}}, {{1, 1}, {1, 1}}, {{1, 0}, {1, 0}}, {{0, 0}, {1, 0}}, {{1, 0}, {1, 1}}} Out[5]= {{{{0, 0}, {1, 1}}, 1}, {{{0, 1}, {1, 0}}, 2}, {{{0, 1}, {0, 0}}, 1}, {{{0, 0}, {0, 0}}, 1}, {{{0, 1}, {1, 1}}, 2}, {{{1, 1}, {1, 1}}, 1}, {{{0, 1}, {0, 1}}, 1}, {{{0, 0}, {0, 1}}, 1}} In[6]:= Dlist = RandomInteger[{0, 1}, {10^5, 2, 2}]; myTally[Dlist] // Timing Out[7]= {0.633001, {{{{1, 1}, {0, 0}}, 6366}, {{{0, 0}, {0, 1}}, 12467}, {{{1, 1}, {0, 1}}, 12633}, {{{0, 1}, {0, 1}}, 12484}, {{{0, 1}, {0, 0}}, 12377}, {{{0, 1}, {1, 0}}, 12402}, {{{0, 0}, {1, 1}}, 6278}, {{{0, 1}, {1, 1}}, 12473}, {{{0, 0}, {0, 0}}, 6303}, {{{1, 1}, {1, 1}}, 6217}}} You can find below a step by step evaluation of the code with some extras that should help to understand what is going on. In[8]:= Dlist = {{{0, 1}, {0, 1}}, {{1, 0}, {1, 0}}, {{1, 0}, {0, 1}}, {{0, 1}, {1, 0}}}; In[9]:= Flatten /@ Dlist Out[9]= {{0, 1, 0, 1}, {1, 0, 1, 0}, {1, 0, 0, 1}, {0, 1, 1, 0}} Out[10]= {5, 10, 9, 6} In[11]:= Map[Reverse, Dlist, {2}] Out[11]= {{{1, 0}, {1, 0}}, {{0, 1}, {0, 1}}, {{0, 1}, {1, 0}}, {{1, 0}, {0, 1}}} In[12]:= Flatten /@ Map[Reverse, Dlist, {2}] Out[12]= {{1, 0, 1, 0}, {0, 1, 0, 1}, {0, 1, 1, 0}, {1, 0, 0, 1}} In[13]:= l2 = Out[13]= {10, 5, 6, 9} In[14]:= Transpose[{l1, l2}] Out[14]= {{5, 10}, {10, 5}, {9, 6}, {6, 9}} In[15]:= l3 = Min /@ Transpose[{l1, l2}] Out[15]= {5, 5, 6, 6} In[16]:= Tally@l3 Out[16]= {{5, 2}, {6, 2}} In[17]:= {IntegerDigits[First@#, 2], Last@#} & /@ Tally@l3 Out[17]= {{{1, 0, 1}, 2}, {{1, 1, 0}, 2}} In[18]:= l4 = {PadLeft[IntegerDigits[First@#, 2], 4], Last@#} & /@ Tally@l3 Out[18]= {{{0, 1, 0, 1}, 2}, {{0, 1, 1, 0}, 2}} In[19]:= {Partition[First@#, 2], Last@#} & /@ l4 Out[19]= {{{{0, 1}, {0, 1}}, 2}, {{{0, 1}, {1, 0}}, 2}} -- === Subject: Re: Tally I'm trying the following: > *Dlist = {{{0,1},{0,1}},{{1,0},{1,0}},{{1,0},{0,1}},{{0,1},{1,0}}};* > The output is: *{{{{0,1},{0,1}},1},{{{1,0},{1,0}},1},{{{1,0},{0,1}},2}}* instead of *{{{{0,1},{0,1}},2},{{{1,0},{0,1}},2}}* If I remove the last member from DList *Dlist = {{{0,1},{0,1}},{{1,0},{1,0}},{{1,0},{0,1}}};* then I got a correct answer *{{{{0,1},{0,1}},2},{{{1,0},{0,1}},1}}.* Is anything wrong with my original code? I really *hope* that I am wrong, but it seems to me that your code is correct. The test function is a good equivalence relation, i.e. it is reflexive, symmetric and transitive, so this cannot be the problem. But something seems to be wrong with Tally: test = dlist = {{{0, 1}, {0, 1}}, {{1, 0}, {1, 0}}, {{1, 0}, {0, 1}}, {{0, 1}, {1, 0}}} test2[p_, q_] := With[{val = test[p, q]}, Print[{Position[dlist, p, {1}], Position[dlist, q, {1}], val}]; val] ( Using Position should work because this specific dlist has no repeating elements ) The output of Tally[dlist, test2] is: {{{1}},{{4}},False} {{{3}},{{2}},False} {{{4}},{{2}},False} {{{4}},{{3}},True} {{{1}},{{3}},False} {{{2}},{{4}},False} {{{4}},{{3}},True} {{{3}},{{1}},False} {{{{0, 1}, {0, 1}}, 1}, {{{1, 0}, {1, 0}}, 1}, {{{1, 0}, {0, 1}}, 2}} It looks like Tally never tests element 1 against element 2, but it does test element 4 against element 3 *twice*, even though this is completely unnecessary. This is the kind of bug that severely undermines one's trust in Mathematica. I do not expect that Integrate or some numerical method should always return a correct answer. I know that this is simply not possible. But the algorithms that could be used by Tally are simple enough that I find this bug quite shocking. === Subject: Re: Tally I dont't think there is anything wrong with your code, but I know that under certain conditions Tally does not work properly. I postet a similar problem re Tally last November to Wolfram support, and I got the answer that Tally is not always working correctly. I suggest you write your own Tally function, e.g. using Sow and Reap. This works fast and perfect in my situations. Michael Weyrauch I'm trying the following: > *Dlist = {{{0,1},{0,1}},{{1,0},{1,0}},{{1,0},{0,1}},{{0,1},{1,0}}};* > The output is: *{{{{0,1},{0,1}},1},{{{1,0},{1,0}},1},{{{1,0},{0,1}},2}}* instead of *{{{{0,1},{0,1}},2},{{{1,0},{0,1}},2}}* If I remove the last member from DList *Dlist = {{{0,1},{0,1}},{{1,0},{1,0}},{{1,0},{0,1}}};* then I got a correct answer *{{{{0,1},{0,1}},2},{{{1,0},{0,1}},1}}.* Is anything wrong with my original code? > Armen === Subject: Re: Tally > I'm trying the following: > *Dlist = {{{0,1},{0,1}},{{1,0},{1,0}},{{1,0},{0,1}},{{0,1},{1,0}}};* > The output is: *{{{{0,1},{0,1}},1},{{{1,0},{1,0}},1},{{{1,0},{0,1}},2}}* instead of *{{{{0,1},{0,1}},2},{{{1,0},{0,1}},2}}* If I remove the last member from DList *Dlist = {{{0,1},{0,1}},{{1,0},{1,0}},{{1,0},{0,1}}};* then I got a correct answer *{{{{0,1},{0,1}},2},{{{1,0},{0,1}},1}}.* Is anything wrong with my original code? Although this does not answer your question, writing your expression as follows should help investigating its behavior (assuming, of course, I have correctly understood what you try to achieve). Dlist={{{0,1},{0,1}},{{1,0},{1,0}},{{1,0},{0,1}},{{0,1},{1,0}}}; Tally[Dlist, ==> {{{{0,1},{0,1}},1},{{{1,0},{1,0}},1},{{{1,0},{0,1}},2}} -- === Subject: Re: Tally > I'm trying the following: >> *Dlist = {{{0,1},{0,1}},{{1,0},{1,0}},{{1,0},{0,1}},{{0,1},{1,0}}};* >> The output is: >> *{{{{0,1},{0,1}},1},{{{1,0},{1,0}},1},{{{1,0},{0,1}},2}}* >> instead of >> *{{{{0,1},{0,1}},2},{{{1,0},{0,1}},2}}* >> If I remove the last member from DList >> *Dlist = {{{0,1},{0,1}},{{1,0},{1,0}},{{1,0},{0,1}}};* >> then I got a correct answer >> *{{{{0,1},{0,1}},2},{{{1,0},{0,1}},1}}.* >> Is anything wrong with my original code? > Although this does not answer your question, writing your expression as > follows should help investigating its behavior (assuming, of course, I > have correctly understood what you try to achieve). Dlist={{{0,1},{0,1}},{{1,0},{1,0}},{{1,0},{0,1}},{{0,1},{1,0}}}; Tally[Dlist, ==> {{{{0,1},{0,1}},1},{{{1,0},{1,0}},1},{{{1,0},{0,1}},2}} An even more compact way of writing the test function is as follows, Unfortunately, it still does not solve the issue... -- === Subject: Hide a PopupMenu in Manipulate the rigth email adress. I have just began learning Mathematica. I could not find the solution to the following problem: I have made a circle and the user should decide, whether the circle should have a color. If it should, three PopupMenus should be shown, but when the checkbox is not clicked, they should not be shown: ---------------------------------------------------------------------------- - (*Code: *) Manipulate[ Graphics[ { If[ color, {typ = PopupMenu; color1, Disk[] }, {typ = None; Circle[] } ]} ], {{color, False, Color}, {False, True}}, {{color1, Blue, Color1}, {Blue -> Blue, Green -> Green}, ControlType -> typ} ] --------------------------------------------------------------------------- But as you can see, you have to recompile it in order to see the changes. Is there any way to do so, without recompiling the code? Patrick Klitzke email:philologos14@gmx.de === Subject: Re: Hide a PopupMenu in Manipulate If you like you can skip Manipulate and instead wrap Dynamic around the expression of interest: Dynamic@Row[ { Graphics[If[colored, {color, Disk[]}, Circle[]]], Checkbox[Dynamic[colored]], Color, If[colored, PopupMenu[Dynamic[color], {Blue -> Blue, Green -> Green}]] }, ] > the rigth email adress. I have just began learning Mathematica. I could > not find the solution to the following problem: > I have made a circle and the user should decide, whether the circle > should have a color. If it should, > three PopupMenus should be shown, but when the checkbox is not clicked, > they should not be shown: > ----------------------------------------------------------------------------- > (*Code: *) > Manipulate[ > Graphics[ > { > If[ > color, > {typ = PopupMenu; > color1, Disk[]}, {typ = None; > Circle[] } > ]} > ], > {{color, False, Color}, {False, True}}, > {{color1, Blue, Color1}, > {Blue -> Blue, Green -> Green}, > ControlType -> typ} > ] > --------------------------------------------------------------------------- > But as you can see, you have to recompile it in order to see the changes. > Is there any way to do so, without recompiling the code? > Patrick Klitzke email:philologo...@gmx.de === Subject: Re: Hide a PopupMenu in Manipulate > the rigth email adress. I have just began learning Mathematica. I could > not find the solution to the following problem: > I have made a circle and the user should decide, whether the circle > should have a color. If it should, > three PopupMenus should be shown, but when the checkbox is not clicked, > they should not be shown: How about disabling the popup menu? Manipulate[Graphics[{If[color,{color1,Disk[]},{Circle[]}]}], {{color,False,Color},{False,True}},{{color1,Blue,Color1},{Blue- >Blue,Green->Green},ControlType->PopupMenu,Enabled->color}] -Rob === Subject: Re: Hide a PopupMenu in Manipulate A colleague suggested using PaneSelector to hide the popup menu when it's not in use: Manipulate[ Graphics[{If[color, c, Black], Circle[{0, 0}, 1]}, ImageSize -> {400, 400}], {{color, True, color on}, {True, False}}, Item[ PaneSelector[ {True -> Row[{ select color, PopupMenu[ Dynamic@c, {Red -> red, Blue -> blue, Green -> green}] }, Spacer[3]], False -> }, Dynamic@color ] ], {{c, Red}, {Red, Blue, Green}, ControlType -> None}, ControlPlacement -> Left] -Rob === Subject: Re: Rotation of 3D objects > Here is some code for those who have the Presentations package. For reflection in a mirror: Needs[Presentations`Master`] Module[ > {(* object to reflect *) > gr = ParametricDraw3D[{t, u + t, u t/5}, {t, 0, 2}, {u, -1, 1}, > Mesh -> 5, > BoundaryStyle -> Black], > (* Mirror location and normal *) > p = {1, 1, 2}, > normal = {0, 0, 1}, > vector1, vector2}, > {vector1, vector2} = NullSpace[{normal}]; > Draw3DItems[ > {(* Original object *) > {Opacity[.7, HTML[DarkSeaGreen]], gr}, > (* Reflected object *) > {Opacity[.7, HTML[DodgerBlue]], gr} // > ReflectionTransformOp[normal, p], > (* Draw the mirror *) > {Opacity[0.3, HTML[SkyBlue]], > ParametricDraw3D[ > p + s vector1 + t vector2, {s, -3, 3}, {t, -3, 3}, > Mesh -> None]}}, > NeutralLighting[0, 0.6, .1], > NiceRotation, > ViewPoint -> {2, -2.4, .6}, > Boxed -> False, > ImageSize -> 300] > ] Multiple copies of rotation about an axis: Module[ > {(* object to reflect *) > gr = ParametricDraw3D[{t, u + t, u t/5}, {t, 0, 2}, {u, -1, 1}, > Mesh -> 5, > BoundaryStyle -> Black], > (* axis, location and number of copies *) > axis = {1, 1, 0}, > axislocation = {-1.5, -1.5, 2}, > ncopies = 4, > rotationangle}, > rotationangle = 2 [Pi]/ncopies; > Draw3DItems[ > {(* Rotations *) > {Opacity[.7, HTML[DarkSeaGreen]], > Table[gr // > RotationTransformOp[n rotationangle, axis, axislocation], {n, = 0, > ncopies - 1}]}, > (* Draw the axis *) > Red, Arrow3D[axislocation, axislocation + 5 axis, {.10}]}, > NeutralLighting[0, 0.6, .1], > NiceRotation, > ViewPoint -> {-1, -2.4, .6}, > Boxed -> False, > ImageSize -> 300] > ] A Manipulate statement allowing the rotation about an axis by an adjustabl= e > angle theta. Manipulate[ > Module[ > {(* object to reflect *) > gr = ParametricDraw3D[{t, u + t, u t/5}, {t, 0, 2}, {u, -1, 1}, > Mesh -> 5, > BoundaryStyle -> Black], > (* axis direction and location *) > axis = {1, 1, 0}, > axislocation = {-1.5, -1.5, 2}}, > Draw3DItems[ > {(* Original object *) > {Opacity[.7, HTML[DarkSeaGreen]], gr}, > (* Rotated object *) > {Opacity[.7, HTML[DodgerBlue]], > gr // RotationTransformOp[[Theta], axis, axislocation]}, > (* Draw the axis *) > Red, Arrow3D[axislocation, axislocation + 5 axis, {.10}]}, > NeutralLighting[0, 0.6, .1], > NiceRotation, > PlotRange -> {{-1, 4}, {-1, 4}, {-1, 5}}, > ViewPoint -> {-1, -2.4, .6}, > Boxed -> False, > ImageSize -> 300] > ], > Style[Rotation about axis by angle [Theta], 16], > {[Theta], 0, 2 [Pi], Appearance -> Labeled}] -- > David Park > djmp...@comcast.nethttp://home.comcast.net/~djmpark/ By what command is it possible to create (without writing a code > separately ): 1) Reflections of 3D objects about a plane? 2) Multiple copies equally spaced by rotation around an axis through > two given points? E.g., > surf = ParametricPlot3D[{ t,u+t, u*t/5}, {t,0,2},{u,-1,1}]; > Rotate[surf,Axis->{ {-1,-1,-1},{1,1,1}} , Copies-> 4 ] ; and, 3) A single rotation of given object through a given angle on an axis > through two defined points? > Narasimham- Hide quoted text - - Show quoted text - Actually in engineering drawing software e.g., CATIA, Autocad Pro E &c. such 3D operations are routinely implemented, clicking on a standard GUI...the mathematical basis of which I was sure is well within Mathematica's range of computational capabilities. ( and it also appeared in 200 seconds. ).Mathematica gives the user an advantage to see those steps, or look into the black box.Of course, some minimum code lines have to be written. Narasimham === Subject: Importing text files I'm using Mathematica v6.02 to import a large comma delimited text file (CSV format). The file is about 700,000 records and takes 241 Mb of space according to ByteCount. The file is a mix of real and string characters. I've imported much smaller versions of this using the built-in support for Excel XLS format without any difficulties. For the larger file, the Import appears to work fine except that all of the string elements import with quotation marks, i.e., if you look at the full form, all of the string elements are expressed as {YES,.....} With the character intact. This is the first I've bumped into this particular issue using Import. Two questions: First, is there a way that I can remove the characters as part of the Import command? And second, if these characters cannot be removed during the Import process, can someone offer an efficient way to remove them from the imported list? -Mark === Subject: Re: Importing text files I'm using Mathematica v6.02 to import a large comma delimited text file (CSV > format). The file is about 700,000 records and takes 241 Mb of space > according to ByteCount. The file is a mix of real and string characters. > I've imported much smaller versions of this using the built-in support > for Excel XLS format without any difficulties. For the larger file, the Import appears to work fine except that all of > the string elements import with quotation marks, i.e., if you look at > the full form, all of the string elements are expressed as {YES,.....} With the character intact. This is the first I've bumped into this > particular issue using Import. Two questions: First, is there a way that I can remove the > characters as part of the Import command? And second, if these > characters cannot be removed during the Import process, can someone > offer an efficient way to remove them from the imported list? > -Mark > Something changed between 6.0.1 and 6.0.2 when you import a CSV file containing character strings. The earlier version stripped off the quotation marks, the later one leaves them in. Since a CSV file can contain strings without quotes, the new way of doing things is more consistent, and probably counts as a bug fix. Have you tried just stripping the quotes afterwards: Import[something.csv] /. x_String:>StringReplace[x,->] If you anticipate going to even larger files, you should be aware that because your file contains both real and string types, it will not pack, and therefore occupies much more space and is slower to process than would otherwise be the case. David Bailey http://www.dbaileyconsultancy.co.uk === Subject: Re: Importing text files On 25 Mar, 06:19, Coleman, Mark I'm using Mathematica v6.02 to import a large comma delimited text file (CSV > format). The file is about 700,000 records and takes 241 Mb of space > according to ByteCount. The file is a mix of real and string characters. > I've imported much smaller versions of this using the built-in support > for Excel XLS format without any difficulties. For the larger file, the Import appears to work fine except that all of > the string elements import with quotation marks, i.e., if you look at > the full form, all of the string elements are expressed as {YES,.....} With the character intact. This is the first I've bumped into this > particular issue using Import. Two questions: First, is there a way that I can remove the > characters as part of the Import command? And second, if these > characters cannot be removed during the Import process, can someone > offer an efficient way to remove them from the imported list? > -Mark Hi The behavior of Import has changed from 6.0.1 to 6.0.2 regarding csv files. In old versions, a string that is surrounded in quotes such as hello was imported as hello but now it is imported as hello . Say I have a csv file called Book1.csv with the following data hello,1 test,2 bode,3 hehehe,4 oidjaojf,5 cfoiuhsrfipvuh,6 fojewhnfrvo,7 werijfbwpiufv,8 nhjawhb,9 cvijweqbv,10 vwjiebv,11 In[2]:= book = Import[Book1.csv] Out[2]= {{hello, 1}, {test, 2}, {bode, 3}, {hehehe, 4}, {oidjaojf, 5}, {cfoiuhsrfipvuh, 6}, {fojewhnfrvo, 7}, {werijfbwpiufv, 8}, {nhjawhb, 9}, {cvijweqbv, 10}, {vwjiebv, 11}} If you don't want the escaped quotes () you can strip them out as follows: In[3]:=f = If[StringQ[#], StringReplace[#, -> ], #] &; In[4]:= Map[f, book, {2}] Out[4]= {{hello, 1}, {test, 2}, {bode, 3}, {hehehe, 4}, {oidjaojf, 5}, {cfoiuhsrfipvuh, 6}, {fojewhnfrvo, 7}, {werijfbwpiufv, 8}, {nhjawhb, 9}, {cvijweqbv, 10}, {vwjiebv, 11}} I don't know if this is the most efficient way but it does the job. === Subject: Re: (Q: How to copy programmatically?) > The proper structure of Notebook[] is Notebook[{cell1, cell2, etc.}, opts]. > This is documented in the documentation for Notebook[]. Actually the documentation for Notebook[] only contains an example, but it is not clear that this is the /only/ acceptable syntax, so it is natural that one starts experimenting. I tried to achieve an effect similar to simply copying plain text from Notepad, i.e. I did not want any style information to be associated with the copied text. I was not sure what style to use with Notebook[{Cell[abc, style]}], so I tried Notebook[{abc}] which appeared to work. (Most probably the style should be Input.) However, your method of writing to the clipboard isn't going to work robustly. > You can read the values off the clipboard notebook pretty robustly, but writing > to the clipboard notebook doesn't always interact with the clipboard as you > would expect. The most robust way of copying something to the clipboard is to create a > temporary, invisible notebook with what you want and execute the Copy front > end token. This method can also allow you to sidestep the issue of creating > correct cells. E.g., nb = NotebookCreate[Visible -> False]; > NotebookWrite[nb, 2+2]; > SelectionMove[nb, All, Notebook]; > FrontEndTokenExecute[nb, Copy]; > NotebookClose[nb]; How would one use CreateDocument[] instead of NotebookCreate[] and NotebookWrite[]? (According to the documentation, NotebookCreate[] is obsolete, and CreateDocument[] can insert an expression into the notebook right after it is created.) Is the following correct and equivalent to nb = NotebookCreate[]; NotebookWrite[nb, 2+2] ? nb = CreateDocument[Cell[BoxData[2+2], Input]]; There are a few places where Mathematica itself uses this technique to > programmatically deliver something to the clipboard. We're working on a design > for a much easier way to do this in future versions. > John Fultz > jfultz@wolfram.com > User Interface Group > Wolfram Research, Inc. > > When pasting quoted text from an e-mail, Mathematica will offer to > remove the quoting marks. It says: > > The text you are pasting appears to be from a quoted email. Do you > want Mathematica to remove the quoting marks before pasting it? (Yes|No) > > Here is a quoted expression to try this: > >> {9, >> 0, >> 7, >> 8, >> 7, >> 2, >> 5, >> 0, >> 7, >> 1} > > The dialogue box also comes up when evaluating the following to access > the clipboard programmatically: > > NotebookGet@ClipboardNotebook[] > > This is expected and understandable. But the dialogue box appears when > using NotebookPut[] too if the clipboard contains a quoted expression! > > NotebookPut[Notebook[{abc}], ClipboardNotebook[]] > > Why does this happen? Is it a bug? Also, is this the correct way to > *copy* a string to the clipboard programmatically? It does work, but I > am not sure if Notebook[{abc}] (with no Cells) is a correct Notebook > expression. (Where is the correct syntax documented?) > === Subject: Re: (Q: How to copy programmatically?) Strange, but nothing of this kind happens on my system: In[97]:= $Version Out[97]= 6.0 for Mac OS X x86 (32-bit) (June 19, 2007) The quote marks are removed automatically and no dialog comes up in all the cases you mention below. Andrzej Kozlowski When pasting quoted text from an e-mail, Mathematica will offer to > remove the quoting marks. It says: The text you are pasting appears to be from a quoted email. Do you > want Mathematica to remove the quoting marks before pasting > it? (Yes|No) Here is a quoted expression to try this: > {9, >> 0, >> 7, >> 8, >> 7, >> 2, >> 5, >> 0, >> 7, >> 1} The dialogue box also comes up when evaluating the following to access > the clipboard programmatically: NotebookGet@ClipboardNotebook[] This is expected and understandable. But the dialogue box appears > when > using NotebookPut[] too if the clipboard contains a quoted expression! NotebookPut[Notebook[{abc}], ClipboardNotebook[]] Why does this happen? Is it a bug? Also, is this the correct way to > *copy* a string to the clipboard programmatically? It does work, > but I > am not sure if Notebook[{abc}] (with no Cells) is a correct Notebook > expression. (Where is the correct syntax documented?) > === Subject: Re: Match Pairs of Numbers lst = {{1, 1}, {1, 2}, {1, 3}, {1, 4}, {2, 2}, {3, 1}, {3, 2}, {3, 3}, {4, 1}, {4, 4}}; Select[lst, MemberQ[DeleteCases[lst, #], Reverse[#]] &] {{1, 3}, {1, 4}, {3, 1}, {4, 1}} Cases[lst, _?(MemberQ[DeleteCases[lst, #], Reverse[#]] &)] {{1, 3}, {1, 4}, {3, 1}, {4, 1}} DeleteCases[lst, _?(FreeQ[DeleteCases[lst, #], Reverse[#]] &)] {{1, 3}, {1, 4}, {3, 1}, {4, 1}} Pick[lst, MemberQ[DeleteCases[lst, #], Reverse[#]] & /@ lst] {{1, 3}, {1, 4}, {3, 1}, {4, 1}} Bob Hanlon > Any help would be appreciated. I am using Mathematica 5.2 & 6.0 I am having trouble finding the correct form of Pattern Matching for > pairs of Numbers. I do not know whether to use Select, Cases, Pick, > etc. I am also unsure how to set the pattern matching argument. Assume I have the list lst = {{1,1}, {1,2}, {1,3}, {1,4}, {2,2}, {3,1}, {3,2}, {3,3}, {4,1}, {4,4}} > I would like to match/select pairs that have the same set of numbers > only reversed, that is, the selection would find {{1,3}, {3,1}, {1,4}, {4,1} } Andrew C Beveridge > MS M888 > Los Alamos National Laboratory > Los Alamos, NM 87545 505-665-2092 > e-mail: acbev@lanl.gov === Subject: Another stylesheet question I went thru the stylesheet tutorial that David Park kindly made available. I was successful in making the new stylesheet he proposed. But I'd like to do something he didn't cover (that I could find). I'd like to simply change the size of the text in the text style (the cell type found in the little box at upper left in a notebook). I can reformat the text cell by cell but I'd like it to just use a proper text size to start with from default.nb. I've given up trying to do this in Options Inspector. I've looked thru it forever and can't find any way to change text size. And if I did, would that change what's in the default.nb stylesheet? So I did Format/ Edit Stylesheet, selected the text style, to modify, then changed it to a new size and color via the Format Menu and then *Save As* default.nb. Well, that didn't work -- Mathematica wouldn't even run on restart. I had to restore default.nb from my backup copy. Even though the Edit Stylesheet window says it is using inherited base definitions from default.nb, the file it makes is tiny and apparently leaves out items needed for Mathematica to run. So I'm missing the big picture -- can someone please tell me how to modify default.nb -- or make Mathematica use a different === Subject: Re: Another stylesheet question I'm not a total expert on this at all and it would still be nice if WRI provided more complete documentation on creating, modifying and using style sheets. A general criticism I have with all the WRI style sheets is that the Text font size is too small. If one looks at textbooks or research papers the text font size is always just as large, if not larger, than the font size used in equations. Mathematica notebooks are the best method there is for technical communications and Text cells are just as important as Input/Output cells. One might even consider making Text cells the default new cell type! Also, Output cells should be unadorned in any way so that if one closed up the Input cells the notebook would look just like a textbook or research paper. I don't think you can, or should, change the Default.nb style sheet. What you should do is modify it and use SaveAs to save it to a new name, say MyDefault.nb, in your personal FrontEnd, StyleSheets folder. -- David Park djmpark@comcast.net http://home.comcast.net/~djmpark/ >I went thru the stylesheet tutorial that David Park kindly > made available. I was successful in making the new > stylesheet he proposed. But I'd like to do something he > didn't cover (that I could find). I'd like to simply change the size of the text in the text > style (the cell type found in the little box at upper left > in a notebook). I can reformat the text cell by cell but I'd > like it to just use a proper text size to start with from > default.nb. I've given up trying to do this in Options > Inspector. I've looked thru it forever and can't find any > way to change text size. And if I did, would that change > what's in the default.nb stylesheet? So I did Format/ Edit Stylesheet, selected the text style, > to modify, then changed it to a new size and color via the > Format Menu and then *Save As* default.nb. Well, that > didn't work -- Mathematica wouldn't even run on restart. I had to > restore default.nb from my backup copy. Even though the Edit > Stylesheet window says it is using inherited base > definitions from default.nb, the file it makes is tiny and > apparently leaves out items needed for Mathematica to run. So I'm missing the big picture -- can someone please tell me > how to modify default.nb -- or make Mathematica use a different > === Subject: Re: Mathematica notebooks the best method Of course there IS a time-limited, cheap student version of Mathematica available. In fact, two such: a 6-month version and a 12-month version. > .... A time limited cheap student version > available to any student, whether at an institution that has a site > license or not, would make an enormous contribution to the adoption of > Mathematica, -- Murray Eisenberg murray@math.umass.edu Mathematics & Statistics Dept. Lederle Graduate Research Tower phone 413 549-1020 (H) University of Massachusetts 413 545-2859 (W) 710 North Pleasant Street fax 413 545-1801 Amherst, MA 01003-9305 === Subject: Re: Mathematica notebooks the best method djvu vs. pdf: no big deal. Tex vs. Mathematica: BIG deal! With djvu and pdf, it's merely a matter of the final format in which the document appears and is disseminated. With (La)TeX and Mathematica, there's a crucial difference in the entire authoring process. Among other things: (1) (La)TeX concentrates upon the logical structure of the document, whereas Mathematica from the start involves the actual appearance of the document. (2) Typing math markup is typically quicker in (La)TeX than in Mathematica, as it avoids Control-key sequences (unless one is using an editor where such sequences are used as shortcuts) or at least uses shorter keystroke-only sequences. (3) Mathematica allows live calculations in the document itself, whereas TeX does not (except of the most primitive kind). Exception: a specialized TeX+CAS system. (4) Mathematica creates graphics of all sorts directly in the document, whereas with the exception of a limited number of native or package add-on graphics types, graphics must be imported into a TeX document from an external source (such as Mathematica)! There are two other another differences: (5) One can have an entire TeX document preparation system -- editor, TeX engine plus packages, viewer, and converter (dvi to ps or pdf, e.g.) -- for free. Needless to say, Mathematica is not free. (6) The source code for TeX and many or most of the supporting utilities is open source; this is certainly not the case for Mathematica. ...I would like to point out that publishing standards are not > set in stone. For several years I have witnessed PDF visibly loosing > ground to djvu in the mathematical preprint area. I like with many > other things I learned about it first form students, who quickly > understood its technical superiority over PDF (most of all, much > smaller file size). Now I see that a number of on-line mathematics > journals are offering djvu as an alternative to pdf. -- Murray Eisenberg murray@math.umass.edu Mathematics & Statistics Dept. Lederle Graduate Research Tower phone 413 549-1020 (H) University of Massachusetts 413 545-2859 (W) 710 North Pleasant Street fax 413 545-1801 Amherst, MA 01003-9305 === Subject: Re: Mathematica notebooks the best method for technical communications (Was: Another stylesheet question) I agree that the persuading the academic and publishing establishment to add Mathematica to the so called publishing standards is going to be an uphill struggle and probably not worth the effort. But I do not agree about the reasons for this and of course I totally disagree with the final statement. The academic establishment is one of the most conservative establishments there are. The reason for this is clear: it consist mostly of people who are oldish or quite old and thus reluctant to learn ways of doing this different from those that they learned in their youth, particularly if they lie outside their own academic area. In so called research institutions young people are expected and in fact have to, if they are going to stay around, concentrate on research and being concerned with stuff like publishing formats is not going to get one tenure at Stanford. So naturally the people who dominate this area are the older, tenured staff. The publishing world is even worse. The reluctance to adopt technical innovation in academic publishing would be a good subject for a comedy if it wasn't so depressing in its consequences. I have also had quite a lot of contact with this for a number of years. For example I still remember the days when one of the leading mathematical journals started using TeX. Even after they started it, they continued to demand that authors professional typist. I think I must have been one of the earliest Springer authors who used TeX and I remember how none of the editors knew what it was and how much trouble I had when I wanted to modify some of their macros. It was years after TeX had become standard for writing mathematical research. The same thing is happening nowadays with the transfer to electronic publishing. So I agree, the chances of convincing the academic or publishing establishment that they should try to adopt another format are pretty slim. However, there is another way, and I hope WRI is pursuing it. A long time before TeX was adopted by journals and before most senior academics understood how it it suppose to be pronounced, it had become de facto standard among students and young researchers. Being young they learn new things much faster, are much more likely to experiment with them by themselves (so usually they do not care about printed manuals) and appreciate genuine innovation as oppose to hype. What they are mostly concerned with is price and whether the things they learn would be of advantage in their future employment. This suggest an obvious strategy for WRI: ignore the academic establishment and concentrate on the students and their likely future employers. I don't know much about the latter but from the statistics I have seen Mathematica is doing not to badly in this area, at least compared with its major competitors. As for students, what is obviously needed access to cheap copies, other than through piracy (though I hope WRI is not completely blind to the benefits it gets from that latter phenomenon as long as it is restricted to students). By the way, the current system of student versions isn't really sufficient since it requires universities to have site licenses, which in turn requires winning over the establishment. A time limited cheap student version available to any student, whether at an institution that has a site license or not, would make an enormous contribution to the adoption of Mathematica, and would make opinions like that at the end of the OPs post largely irrelevant. Finally, I would like to point out that publishing standards are not set in stone. For several years I have witnessed PDF visibly loosing ground to djvu in the mathematical preprint area. I like with many other things I learned about it first form students, who quickly understood its technical superiority over PDF (most of all, much smaller file size). Now I see that a number of on-line mathematics journals are offering djvu as an alternative to pdf. Andrzej Kozlowski > Mathematica notebooks are the best method there is for >> technical communications Would this were true. It's not. Making Mathematica notebooks become the primary method for both > preparing *and communicating* technical communications (broadly > interpreted to include teaching, writing, presentations, and > publications) in both the academic and professional worlds might be a > laudable goal, and a number of people (David Park very much included) > have put sincere and laudable efforts into trying to make it be the > case. Sorry, it's _not_ going to happen. Wolfram is partly to blame for this -- very much including the > currently > ongoing version 6 documentation disaster. But there are also very major and fundamental reasons why this goal > very > possibly should not happen, or should not be attempted, or simply > could > never happen in any case. To focus on just one aspect of this topic (out of many), I would point > out that major professional societies have (since Isaaac Newton's > time!) > carried the burden of developing two of the major worldwide channels > of > technical and scientific communications, namely scientific and > technical > journals (and archives), and scientific and technical meetings And, these societies are struggling to adapt, and in many ways > successfully adapting, today to the Internet, electronic technologies, > open access, and other emerging complexities of information > transmission and communication. It's an expensive and > resource-consuming struggle The primary communication methods or formats for user input of > technical material to essentially all such journals and meetings > today > -- user input being of course the primary source for all such > material-- are TeX (or LaTeX), PDF, and (unfortunately, but it's the > reality) MSWord. I've been heavily involved with a couple of these societies, and a > close > observer at least, if not a major contributor, to the major and > stressful evolution of professional society publication and meeting > activities and methods in recent years. I've also been a heavy > personal > user of Mathematica since I heard Steven Wolfram introduce version 1 > to > an overflowing auditorium at my university several decades ago. I can only say that I would be a vehement opponent of any proposal > within these societies to divert resources to an effort to add > Mathematica notebooks to the format list above. [And, given the current situation, I'd be a vehement opponent of any > efforts within my university to spend university resources on making > Mathematica a *preferred* and heavily university-supported > computational > and communications technology within my university.] > === Subject: Mathematica notebooks the best method for technical communications (Was: Another stylesheet question) > Mathematica notebooks are the best method there is for > technical communications Would this were true. It's not. Making Mathematica notebooks become the primary method for both preparing *and communicating* technical communications (broadly interpreted to include teaching, writing, presentations, and publications) in both the academic and professional worlds might be a laudable goal, and a number of people (David Park very much included) have put sincere and laudable efforts into trying to make it be the case. Sorry, it's _not_ going to happen. Wolfram is partly to blame for this -- very much including the currently ongoing version 6 documentation disaster. But there are also very major and fundamental reasons why this goal very possibly should not happen, or should not be attempted, or simply could never happen in any case. To focus on just one aspect of this topic (out of many), I would point out that major professional societies have (since Isaaac Newton's time!) carried the burden of developing two of the major worldwide channels of technical and scientific communications, namely scientific and technical journals (and archives), and scientific and technical meetings And, these societies are struggling to adapt, and in many ways successfully adapting, today to the Internet, electronic technologies, open access, and other emerging complexities of information transmission and communication. It's an expensive and resource-consuming struggle The primary communication methods or formats for user input of technical material to essentially all such journals and meetings today -- user input being of course the primary source for all such material -- are TeX (or LaTeX), PDF, and (unfortunately, but it's the reality) MS Word. I've been heavily involved with a couple of these societies, and a close observer at least, if not a major contributor, to the major and stressful evolution of professional society publication and meeting activities and methods in recent years. I've also been a heavy personal user of Mathematica since I heard Steven Wolfram introduce version 1 to an overflowing auditorium at my university several decades ago. I can only say that I would be a vehement opponent of any proposal within these societies to divert resources to an effort to add Mathematica notebooks to the format list above. [And, given the current situation, I'd be a vehement opponent of any efforts within my university to spend university resources on making Mathematica a *preferred* and heavily university-supported computational and communications technology within my university.] === Subject: Re: Another stylesheet question > I went thru the stylesheet tutorial that David Park kindly > made available. I was successful in making the new > stylesheet he proposed. But I'd like to do something he > didn't cover (that I could find). I'd like to simply change the size of the text in the text > style (the cell type found in the little box at upper left > in a notebook). I can reformat the text cell by cell but I'd > like it to just use a proper text size to start with from > default.nb. I've given up trying to do this in Options > Inspector. I've looked thru it forever and can't find any > way to change text size. And if I did, would that change > what's in the default.nb stylesheet? So I did Format/ Edit Stylesheet, selected the text style, > to modify, then changed it to a new size and color via the > Format Menu and then *Save As* default.nb. Well, that > didn't work -- Mathematica wouldn't even run on restart. I had to > restore default.nb from my backup copy. Even though the Edit > Stylesheet window says it is using inherited base > definitions from default.nb, the file it makes is tiny and > apparently leaves out items needed for Mathematica to run. So I'm missing the big picture -- can someone please tell me > how to modify default.nb -- or make Mathematica use a different > Hi Jerry, You should give the altered notebook a new name, eg. jerrystyle.nb and place it somewhere in $UserBaseDirectory/SystemFiles/FrontEnd/Stylesheets. Your style will now appear in the Format/Stylesheet selection. In the options inspector search for DefaultStyleDefinitions and set them to the full path to your new stylesheet to make it the default. Gruss Peter -- ==-==-==-==-==-==-==-==-==-==-==-==-==-==-==-==-==-==-==-==-==-== Peter Breitfeld, Bad Saulgau, Germany -- http://www.pBreitfeld.de === Subject: Re: Number of monomials > In[1]:=Length[f[1]+f[2]+f[3]] > Out[1]:=3 > OK! > In[2]:=Length[f[1]+f[2]] > Out[2]:=2 > OK! > In[3]:=Length[f[1]] > Out[3]:=0 > ??????????? > Who understand let share with me, please! Artur The problem does not occurs in versions 5.2 and 6.02 === Subject: Number of monomials In[1]:=Length[f[1]+f[2]+f[3]] Out[1]:=3 OK! In[2]:=Length[f[1]+f[2]] Out[2]:=2 OK! In[3]:=Length[f[1]] Out[3]:=0 ??????????? Who understand let share with me, please! Artur === Subject: Re: Number of monomials > In[1]:=Length[f[1]+f[2]+f[3]] > Out[1]:=3 > OK! > In[2]:=Length[f[1]+f[2]] > Out[2]:=2 > OK! > In[3]:=Length[f[1]] > Out[3]:=0 > ??????????? > Who understand let share with me, please! Please *do not* use the reply button when you want to start a new topic! If you do, the message will still be grouped with the old thread in Google Groups and in many newsreaders, shadowing the original subject line of the discussion. This is very annoying. Also, please do not cheat when posting examples. The label In[1] suggests that you evaluated this expression in a fresh kernel, but this cannot be the case. Only the lengths of atomic expressions, like numbers or symbols, is 0, so the function f must have been defined in your example. To count the number of terms in a sum, use e.g. Length[{ Sequence@@sum }] I suggest reading this tutorial: tutorial/ExpressionsOverview === Subject: Re: Number of monomials I have version 5.2 ARTUR Gulliet pisze: > In[1]:=Length[f[1]+f[2]+f[3]] >> Out[1]:=3 >> OK! >> In[2]:=Length[f[1]+f[2]] >> Out[2]:=2 >> OK! >> In[3]:=Length[f[1]] >> Out[3]:=0 >> ??????????? >> Who understand let share with me, please! Weird. Works fine (that is Length[f[1]] returns 1 as expected) on my > system (Mac Os X 10.0.2 Leopard - Mathematica 6.0.2). What system were > you using? > In[1]:= Length[f[1] + f[2] + f[3]] Out[1]= 3 In[2]:= Length[f[1] + f[2]] Out[2]= 2 In[3]:= Length[f[1]] Out[3]= 1 In[4]:= $Version Out[4]= 6.0 for Mac OS X x86 (64-bit) (February 7, 2008) === Subject: Re: Number of monomials > In[1]:=Length[f[1]+f[2]+f[3]] > Out[1]:=3 > OK! > In[2]:=Length[f[1]+f[2]] > Out[2]:=2 > OK! > In[3]:=Length[f[1]] > Out[3]:=0 > ??????????? > Who understand let share with me, please! Weird. Works fine (that is Length[f[1]] returns 1 as expected) on my system (Mac Os X 10.0.2 Leopard - Mathematica 6.0.2). What system were you using? In[1]:= Length[f[1] + f[2] + f[3]] Out[1]= 3 In[2]:= Length[f[1] + f[2]] Out[2]= 2 In[3]:= Length[f[1]] Out[3]= 1 In[4]:= $Version Out[4]= 6.0 for Mac OS X x86 (64-bit) (February 7, 2008) -- === Subject: Re: Number of monomials > In[1]:=Length[f[1]+f[2]+f[3]] > Out[1]:=3 > OK! > In[2]:=Length[f[1]+f[2]] > Out[2]:=2 > OK! > In[3]:=Length[f[1]] > Out[3]:=0 > ??????????? It does not happen for me: In[10]:= ClearAll[f] In[11]:= Length[f[1]+f[2]+f[3]] Out[11]= 3 In[12]:= Length[f[1]+f[2]] Out[12]= 2 In[13]:= Length[f[1]] Out[13]= 1 > Who understand let share with me, please! my guess is that there are definitions for f: In[7]:= f[x_]:=a^x In[8]:= Length[f[1]+f[2]] Out[8]= 2 In[9]:= Length[f[1]] Out[9]= 0 You also should have a look at the FullForm of your expressions, which will probably give you a clue about what's going on: ClearAll[f] In[14]:= FullForm[f[1]+f[2]] Out[14]//FullForm= Plus[f[1],f[2]] In[15]:= FullForm[f[1]] Out[15]//FullForm= f[1] In[16]:= FullForm[a] Out[16]//FullForm= a hth, albert === Subject: Re: Another stylesheet question the Options Inspector. > Hi Jerry, You should give the altered notebook a new name, eg. jerrystyle.nb > and place it somewhere in > $UserBaseDirectory/SystemFiles/FrontEnd/Stylesheets. > Your style will now appear in the Format/Stylesheet selection. > In the options inspector search for DefaultStyleDefinitions and set > them to the full path to your new stylesheet to make it the default. Gruss Peter === Subject: Series and Sqrt problem (a bug?) Numerically Mathematica defines square root of a positive number as a positive number: In[1]:= Sqrt[2.] Out[1]= 1.41421 It is careful enough not to simplify a square root of a square: In[2]:= Sqrt[x^2] Out[2]= Sqrt[x^2] because x can be either positive or negative. However, when I specify that x approaches minus infinity, and use Series, it assumes that Sqrt[x^2] is equal to x: In[4]:= Series[Sqrt[x^2], {x, -Infinity, 1}] // Normal Out[4]= x It does the same thing when x approached plus infinity: In[5]:= Series[Sqrt[x^2], {x, Infinity, 1}] // Normal Out[5]= x This does not seem right to me, and caused grievances in my recent research problem. GS === Subject: Re: Series and Sqrt problem (a bug?) > Numerically Mathematica defines square root of a positive number as a > positive number: > In[1]:= Sqrt[2.] > Out[1]= 1.41421 It is careful enough not to simplify a square root of a square: > In[2]:= Sqrt[x^2] > Out[2]= Sqrt[x^2] > because x can be either positive or negative. However, when I specify that x approaches minus infinity, and use > Series, it assumes that Sqrt[x^2] is equal to x: > In[4]:= Series[Sqrt[x^2], {x, -Infinity, 1}] // Normal > Out[4]= x It does the same thing when x approached plus infinity: > In[5]:= Series[Sqrt[x^2], {x, Infinity, 1}] // Normal > Out[5]= x This does not seem right to me, and caused grievances in my recent > research problem. In case it might help, note that In[11]:= Assuming[a < 0, Simplify[Normal[Series[Sqrt[x^2], {x, a, 1}]]]] Out[11]= -x David === Subject: Re: Series and Sqrt problem (a bug?) using Abs[x] instead of Sqrt[x^2] may help. > Numerically Mathematica defines square root of a positive number as a > positive number: > In[1]:= Sqrt[2.] > Out[1]= 1.41421 It is careful enough not to simplify a square root of a square: > In[2]:= Sqrt[x^2] > Out[2]= Sqrt[x^2] > because x can be either positive or negative. However, when I specify that x approaches minus infinity, and use > Series, it assumes that Sqrt[x^2] is equal to x: > In[4]:= Series[Sqrt[x^2], {x, -Infinity, 1}] // Normal > Out[4]= x It does the same thing when x approached plus infinity: > In[5]:= Series[Sqrt[x^2], {x, Infinity, 1}] // Normal > Out[5]= x This does not seem right to me, and caused grievances in my recent > research problem. > GS > === Subject: Using ShowLegend with MultipleListPlot Here is my question: (in Mathematica 5.2) I have a GraphicsArray of some MultipleListPlots. I can't get the symbols to show up in the legend. PlotSymbol isn't a graphics primitive (graphics::gprim is the error) How do turn them back into graphics primitives? Map[Graphics,symbolList] doesn't work. symbolList={PlotSymbol[Triangle,Filled->False],MakeSymbol[{Line[{{0,-3},{0,3 }}],Line[{{-3,0},{3,0}}]}]} It would be nice if there were just a default list of symbols for such a plot. This doesn't seem like an esoteric task, yet there are no examples towards this end. Perhaps in a later version... -- Philip Schiff Department of Physics State University of New York Stony Brook, NY 11790 (631) 371-1025 === Subject: Problems with differentiating Piecewise functions If I set up a piecewise function and differentiate it: In[112]:= pw1 = Piecewise[{{x^2, x <= 0}, {x, x > 0}}] Out[112]= [Piecewise] { {x^2, x <= 0}, {x, x > 0} } In[113]:= pw1 /. x -> 0 Out[113]= 0 In[114]:= pw1d = D[pw1, x] Out[114]= [Piecewise] { {2 x, x < 0}, {1, x > 0}, {Indeterminate, !(* TagBox[True, PiecewiseDefault, AutoDelete->False, DeletionWarning->True])} } In[115]:= pw1d /. x -> 0 Out[115]= Indeterminate Then at the joins between the pieces I get Indeterminate values, because the limit x <= 0 has become x < 0 after differentiation. Does anyone know a solution to this problem? Howard. === Subject: Re: Problems with differentiating Piecewise functions Although you can often get away with argumentless definitions, I think it is always better to define functions with argument patterns. pw1[x_] = Piecewise[{{x^2, x <= 0}, {x, x > 0}}] Then you can get the derivative by simply writing pw1'[x] The derivative is undefined at x == 0 so Mathematica is correct. -- David Park djmpark@comcast.net http://home.comcast.net/~djmpark/ > If I set up a piecewise function and differentiate it: In[112]:= pw1 = Piecewise[{{x^2, x <= 0}, {x, x > 0}}] Out[112]= [Piecewise] { > {x^2, x <= 0}, > {x, x > 0} > } In[113]:= pw1 /. x -> 0 Out[113]= 0 In[114]:= pw1d = D[pw1, x] Out[114]= [Piecewise] { > {2 x, x < 0}, > {1, x > 0}, > {Indeterminate, !(* > TagBox[True, > PiecewiseDefault, > AutoDelete->False, > DeletionWarning->True])} > } In[115]:= pw1d /. x -> 0 Out[115]= Indeterminate Then at the joins between the pieces I get Indeterminate values, > because the limit x <= 0 has become x < 0 after differentiation. Does > anyone know a solution to this problem? > Howard. > === Subject: Re: Problems with differentiating Piecewise functions > If I set up a piecewise function and differentiate it: In[112]:= pw1 = Piecewise[{{x^2, x <= 0}, {x, x > 0}}] Out[112]= [Piecewise] { > {x^2, x <= 0}, > {x, x > 0} > } In[113]:= pw1 /. x -> 0 Out[113]= 0 In[114]:= pw1d = D[pw1, x] Out[114]= [Piecewise] { > {2 x, x < 0}, > {1, x > 0}, > {Indeterminate, !(* > TagBox[True, > PiecewiseDefault, > AutoDelete->False, > DeletionWarning->True])} > } In[115]:= pw1d /. x -> 0 Out[115]= Indeterminate Then at the joins between the pieces I get Indeterminate values, > because the limit x <= 0 has become x < 0 after differentiation. Does > anyone know a solution to this problem? Mathematica is perfectly correct in claiming that the derivative of pw1 at x equals zero, i.e. pw1d(0), does not exist (or undefined or indeterminate). For a derivative at a point is the *limit*, _if this limit exists_, of a difference quotient, that is the limit on the right and the limit on the left to the point must be equal. Or think of the derivative as the slope of the tangent to the curve: the slope of the tangent must be the same on the right and on the left, for a given point. A classical example of an elementary function continuous but not differentiable at zero is the absolute value function. The slope of the tangent is -1 for all negative values and +1 for all positive values, thus the derivative does not exist at 0. I would advise to brush up some of your calculus, for instance by looking at the entry Derivative, especially the section titled Continuity and differentiability in Wikipedia (or in any Calculus book). See http://en.wikipedia.org/wiki/Derivative (Note that the example you provided comes from the online help, and it is very unlikely that WRI publishes erroneous examples.) -- === Subject: Re: Problems with differentiating Piecewise functions > If I set up a piecewise function and differentiate it: In[112]:= pw1 = Piecewise[{{x^2, x <= 0}, {x, x > 0}}] Out[112]= [Piecewise] { > {x^2, x <= 0}, > {x, x > 0} > } In[113]:= pw1 /. x -> 0 Out[113]= 0 In[114]:= pw1d = D[pw1, x] Out[114]= [Piecewise] { > {2 x, x < 0}, > {1, x > 0}, > {Indeterminate, !(* > TagBox[True, > PiecewiseDefault, > AutoDelete->False, > DeletionWarning->True])} > } In[115]:= pw1d /. x -> 0 Out[115]= Indeterminate Then at the joins between the pieces I get Indeterminate values, > because the limit x <= 0 has become x < 0 after differentiation. Does > anyone know a solution to this problem? It's not a problem; Mathematica's result is correct because your function is not differentiable at 0. (Note that, at 0, the derivatives from left and right are 0 and 1, resp.) Consider an example in which the function _is_ differentiable at the join between the pieces: In[16]:= D[Piecewise[{{x^2, x <= 0}, {x^3, x > 0}}], x] Out[16]= Piecewise[{{2*x, x < 0}, {0, x == 0}}, 3*x^2] This is also handled correctly by Mathematica. David === Subject: Re: Problems with differentiating Piecewise functions the derivative does *not* exist at x->0 and Mathematica is right. It has nothing to do with the original definition of your function. > If I set up a piecewise function and differentiate it: In[112]:= pw1 = Piecewise[{{x^2, x <= 0}, {x, x > 0}}] Out[112]= [Piecewise] { > {x^2, x <= 0}, > {x, x > 0} > } In[113]:= pw1 /. x -> 0 Out[113]= 0 In[114]:= pw1d = D[pw1, x] Out[114]= [Piecewise] { > {2 x, x < 0}, > {1, x > 0}, > {Indeterminate, !(* > TagBox[True, > PiecewiseDefault, > AutoDelete->False, > DeletionWarning->True])} > } In[115]:= pw1d /. x -> 0 Out[115]= Indeterminate Then at the joins between the pieces I get Indeterminate values, > because the limit x <= 0 has become x < 0 after differentiation. Does > anyone know a solution to this problem? > Howard. > === Subject: Re: Problems with differentiating Piecewise functions > If I set up a piecewise function and differentiate it: In[112]:= pw1 = Piecewise[{{x^2, x <= 0}, {x, x > 0}}] Out[112]= [Piecewise] { > {x^2, x <= 0}, > {x, x > 0} > } In[113]:= pw1 /. x -> 0 Out[113]= 0 In[114]:= pw1d = D[pw1, x] Out[114]= [Piecewise] { > {2 x, x < 0}, > {1, x > 0}, > {Indeterminate, !(* > TagBox[True, > PiecewiseDefault, > AutoDelete->False, > DeletionWarning->True])} > } In[115]:= pw1d /. x -> 0 Out[115]= Indeterminate Then at the joins between the pieces I get Indeterminate values, > because the limit x <= 0 has become x < 0 after differentiation. Does > anyone know a solution to this problem? Mathematically it makes sense. The derivative cannot be defined in that point. You could manually replace Indeterminate with whichever value you need there: D[pw1, x] /. Indeterminate -> a or D[pw1, x] /. Indeterminate -> 0 === Subject: Colorfunction based upon flux direction I'm quite new at using Mathematica and I am attempting to assign colors to vector field data (3d magnetic flux) using the ListVectorFieldPlot3D function. I would like to assign colors to the vectors based upon the direction in which they point. Hue gives me a color based upon vector magnitude - is there a simple way to color vectors based upon direction? Patrick Keith-Hynes University of Virginia Physics === Subject: Re: Colorfunction based upon flux direction what direction ? in 2d there is only one angle and you can use the cyclic Hue[] color to draw the scalar angle as direction but in 3d ?? Needs[VectorFieldPlots`] plt = ListVectorFieldPlot3D[ Flatten[Table[{{i, j, k}, {i, 2 j, -k}}, {i, 0, 1, 0.1}, {j, 0, 1, 0.1}, {k, 0, 1, 0.1}], 2], ScaleFactor -> 0.2] and Off[ArcTan::indet] (plt /. Line[{p1_, p2_}] :> {Hue[ArcTan @@ Take[p2 - p1, 2]/(2 Pi)], Line[{p1, p2}]}) /. Hue[_Interval] :> Sequence[] may give you an idea. I'm quite new at using Mathematica and I am attempting to assign > colors to vector field data (3d magnetic flux) using the > ListVectorFieldPlot3D function. I would like to assign colors to the > vectors based upon the direction in which they point. Hue gives me a > color based upon vector magnitude - is there a simple way to color > vectors based upon direction? > Patrick Keith-Hynes > University of Virginia Physics === Subject: Re: Intersection of 2D Surfaces in 3D > Following is an example (slightly altered) given in intersection of >> 2- >> D curves with one real root. >> c1 = {x - (t^2 - 1), y - (s^3 + s - 4) }; >> c2 = {x - (s^2 + s + 5), y - (t^2 + 7 t - 2) }; >> It uses NSolve[Join[c1, c2], {x, y}, {s, t}] for supplying real >> roots >> of 2D curves in 2D itself. >> Next, how to generalize further to Solve and find real intersection >> curves of two parameter surfaces in 3-D by extending the same >> Mathematica Join procedure? >> And how to Show the one parameter 3D space curve of intersection so >> obtained ? The following attempt of course fails. >> c3 = {x - (t^2 - 1), y - (s^3 + s - 4), z - (t + s)}; >> c4 = {x - (s^2 + s + 5), y - (t^2 + 7 t - 2),z -( t + s^2/2)}; >> NSolve[Join[c3, c4], {x, y, z}, {t,s}]; >> FindRoot also was not successful. >> Narasimham > Your two surfaces do not interesect: In[58]:= GroebnerBasis[Join[c3, c4], {x, y, s, t}] > Out[58]= {1} So what do you mena by fails? What would constitute a success > here? Andrzek Kozlowski Actually, it should have been In[60]:= GroebnerBasis[Join[c3, c4], {x, y, z}, {s, t}] Out[60]= {1} But they still do not intersect. Andrzej === Subject: Re: Intersection of 2D Surfaces in 3D > Following is an example (slightly altered) given in intersection of 2- > D curves with one real root. c1 = {x - (t^2 - 1), y - (s^3 + s - 4) }; > c2 = {x - (s^2 + s + 5), y - (t^2 + 7 t - 2) }; These are not curves. To get a curve you would use one parameter, not two. Your intersection points are an artifact from using the same two parameters in each definition. > It uses NSolve[Join[c1, c2], {x, y}, {s, t}] for supplying real roots > of 2D curves in 2D itself. Next, how to generalize further to Solve and find real intersection > curves of two parameter surfaces in 3-D by extending the same > Mathematica Join procedure? And how to Show the one parameter 3D space curve of intersection so > obtained ? The following attempt of course fails. c3 = {x - (t^2 - 1), y - (s^3 + s - 4), z - (t + s)}; > c4 = {x - (s^2 + s + 5), y - (t^2 + 7 t - 2),z -( t + s^2/2)}; > NSolve[Join[c3, c4], {x, y, z}, {t,s}]; FindRoot also was not successful. Narasimham You can get the implicit form of the intersection as below. Notice that I use diffferent parameters for the two surfaces. c3 = {x - (t1^2-1), y - (s1^3+s1-4), z - (t1+s1)}; c4 = {x - (s2^2+s2+5), y - (t2^2+7*t2-2), z - (t2 + s2^2/2)}; InputForm[Timing[gb = GroebnerBasis[Join[c3,c4], {x,y,z}, {t1,s1,t2,s2}, MonomialOrder->EliminationOrder]]] Out[20]//InputForm= {0.03200199999999967, {7483 - 4068*x + 736*x^2 - 48*x^3 + x^4 - 564*y + 176*x*y - 8*x^2*y + 16*y^2 + 7360*z - 2848*x*z + 284*x^2*z - 8*x^3*z - 368*y*z + 32*x*y*z + 2756*z^2 - 560*x*z^2 + 24*x^2*z^2 - 32*y*z^2 + 368*z^3 - 32*x*z^3 + 16*z^4, 12 - 8*x - 5*x^2 - x^3 + 8*y + y^2 - 32*z - 24*x*z - 8*y*z - 6*x*y*z + 4*z^2 + 6*x*z^2 + 3*x^2*z^2 - 8*z^3 - 2*y*z^3 - z^4 - 3*x*z^4 + z^6}} This might or might not be (rationally) parametrizable. You could try to get a description of the real parts using Reduce[gb==0, {x,y,z}, Reals] This is computationally intensive. It will give an algebraic (but not rational) parametrization of the intersection curve. Interestingly, there seems to be an isolated point around {x -> 3.27266, y -> -14.6193, z -> -4.11367} A more efficient approach, if you can find points on each intersection curve (real topological) component, might be to use homotopy tracking to trace out the curve sections. Daniel Lichtblau Wolfram Research === Subject: Re: Intersection of 2D Surfaces in 3D >> Following is an example (slightly altered) given in intersection >> of 2- >> D curves with one real root. >> c1 = {x - (t^2 - 1), y - (s^3 + s - 4) }; >> c2 = {x - (s^2 + s + 5), y - (t^2 + 7 t - 2) }; >> It uses NSolve[Join[c1, c2], {x, y}, {s, t}] for supplying real >> roots >> of 2D curves in 2D itself. >> Next, how to generalize further to Solve and find real intersection >> curves of two parameter surfaces in 3-D by extending the same >> Mathematica Join procedure? >> And how to Show the one parameter 3D space curve of intersection so >> obtained ? The following attempt of course fails. >> c3 = {x - (t^2 - 1), y - (s^3 + s - 4), z - (t + s)}; >> c4 = {x - (s^2 + s + 5), y - (t^2 + 7 t - 2),z -( t + s^2/2)}; >> NSolve[Join[c3, c4], {x, y, z}, {t,s}]; >> FindRoot also was not successful. >> Narasimham > Your two surfaces do not interesect: In[58]:= GroebnerBasis[Join[c3, c4], {x, y, s, t}] > Out[58]= {1} So what do you mena by fails? What would constitute a success > here? Andrzek Kozlowski >> Actually, it should have been >> In[60]:= GroebnerBasis[Join[c3, c4], {x, y, z}, {s, t}] >> Out[60]= {1} >> But they still do not intersect. >> Andrzej > I was too quick in replying both times. What this shows is not that > the two surfaces do not intersect but only that you can's > simultaneusly choose values of t and s which give a point of > intersection. This is a rather different matter. If we want to find > a point of intersection rather than a point of intersection which > corresponds to the same values of the parameters, we have to treat > the parameters as independent. One way to proceed is as follows: c3 = {x - (t^2 - 1), y - (s^3 + s - 4), z - (t + s)}; > c4 = {x - (s^2 + s + 5), y - (t^2 + 7 t - 2), z - (t + s^2/2)}; > g1 = GroebnerBasis[c3, {x, y, z}, {t, s}]; > g2 = GroebnerBasis[c4, {x, y, z}, {t, s}]; g = GroebnerBasis[Join[g1, g2], {x, y, z}, > MonomialOrder -> EliminationOrder]; > {x^4 - 8*z*x^3 - 48*x^3 + 24*z^2*x^2 - 8*y*x^2 + > 284*z*x^2 + 736*x^2 - 32*z^3*x - 560*z^2*x + > 176*y*x + 32*y*z*x - 2848*z*x - 4068*x + 16*z^4 + > 368*z^3 + 16*y^2 - 32*y*z^2 + 2756*z^2 - 564*y - > 368*y*z + 7360*z + 7483, z^6 - 3*x*z^4 - z^4 - > 2*y*z^3 - 8*z^3 + 3*x^2*z^2 + 6*x*z^2 + 4*z^2 - > 24*x*z - 6*x*y*z - 8*y*z - 32*z - x^3 - 5*x^2 + > y^2 - 8*x + 8*y + 12} > Now, sols = NSolve[g == 0, {x, y, z}, WorkingPrecision -> 100]; During evaluation of In[11]:= NSolve::infsolns : Infinite > solution set has dimension at least 1 . Returning intersection of > solutions with (28373 x)/30371-(85901 y)/60742+z == 1. > I have supressed the solutions but we can check one of them: In[7]:= Chop[g1 /. First[sols]] > Out[7]= {0} > In[8]:= Chop[g2 /. First[sols]] > Out[8]= {0} So we certianly do have solutions, even an infinte set of solutions, > but none of them correspond to the same values of s and t. I am not > sure if that is what you wanted or not. Andrzej Kozlowski > I forgot one more thing. You can find the values of the parameters for the first solution found above as follows: NSolve[(c3 /. First[sols]) == 0, {s, t}] {{s -> 3.549649428657260104932443969260755059663642737812956488470786773966849 2775489851837406342999953561, t -> 7.562957404816345688590727527777101428342711747001146114563829849367947 862694294555522868386703745}} NSolve[(c4 /. First[sols]) == 0, {s, t}] {{s -> 6.672748755328489446097987376875561309724427484 152028039873269711214036255449691579354919898061403784 966277486576522`97.82414841138389, t -> -11.150181142395346761511766038113142308533135 511733012971341431406359825329246519556023310261923416 0390610285182674971`97.82414841138389}} In general the algebraic surface that you get by eliminating the parameters is may contian the original parametric one, so one would need to actually find the corresponding parameters to determine if the solutions really lie on the parametric surfaces. In addition, one has to decide whehter one is looking only for real solutions or also for complex ones. Andrzej Kozlowski === Subject: Re: Intersection of 2D Surfaces in 3D Following is an example (slightly altered) given in intersection > of 2- > D curves with one real root. c1 = {x - (t^2 - 1), y - (s^3 + s - 4) }; > c2 = {x - (s^2 + s + 5), y - (t^2 + 7 t - 2) }; It uses NSolve[Join[c1, c2], {x, y}, {s, t}] for supplying real > roots > of 2D curves in 2D itself. Next, how to generalize further to Solve and find real intersection > curves of two parameter surfaces in 3-D by extending the same > Mathematica Join procedure? And how to Show the one parameter 3D space curve of intersection so > obtained ? The following attempt of course fails. c3 = {x - (t^2 - 1), y - (s^3 + s - 4), z - (t + s)}; > c4 = {x - (s^2 + s + 5), y - (t^2 + 7 t - 2),z -( t + s^2/2)}; > NSolve[Join[c3, c4], {x, y, z}, {t,s}]; FindRoot also was not successful. Narasimham >> Your two surfaces do not interesect: >> In[58]:= GroebnerBasis[Join[c3, c4], {x, y, s, t}] >> Out[58]= {1} >> So what do you mena by fails? What would constitute a success >> here? >> Andrzek Kozlowski > Actually, it should have been In[60]:= GroebnerBasis[Join[c3, c4], {x, y, z}, {s, t}] > Out[60]= {1} But they still do not intersect. Andrzej I was too quick in replying both times. What this shows is not that the two surfaces do not intersect but only that you can's simultaneusly choose values of t and s which give a point of intersection. This is a rather different matter. If we want to find a point of intersection rather than a point of intersection which corresponds to the same values of the parameters, we have to treat the parameters as independent. One way to proceed is as follows: c3 = {x - (t^2 - 1), y - (s^3 + s - 4), z - (t + s)}; c4 = {x - (s^2 + s + 5), y - (t^2 + 7 t - 2), z - (t + s^2/2)}; g1 = GroebnerBasis[c3, {x, y, z}, {t, s}]; g2 = GroebnerBasis[c4, {x, y, z}, {t, s}]; g = GroebnerBasis[Join[g1, g2], {x, y, z}, MonomialOrder -> EliminationOrder]; {x^4 - 8*z*x^3 - 48*x^3 + 24*z^2*x^2 - 8*y*x^2 + 284*z*x^2 + 736*x^2 - 32*z^3*x - 560*z^2*x + 176*y*x + 32*y*z*x - 2848*z*x - 4068*x + 16*z^4 + 368*z^3 + 16*y^2 - 32*y*z^2 + 2756*z^2 - 564*y - 368*y*z + 7360*z + 7483, z^6 - 3*x*z^4 - z^4 - 2*y*z^3 - 8*z^3 + 3*x^2*z^2 + 6*x*z^2 + 4*z^2 - 24*x*z - 6*x*y*z - 8*y*z - 32*z - x^3 - 5*x^2 + y^2 - 8*x + 8*y + 12} Now, sols = NSolve[g == 0, {x, y, z}, WorkingPrecision -> 100]; During evaluation of In[11]:= NSolve::infsolns : Infinite solution set has dimension at least 1 . Returning intersection of solutions with (28373 x)/30371-(85901 y)/60742+z == 1. I have supressed the solutions but we can check one of them: In[7]:= Chop[g1 /. First[sols]] Out[7]= {0} In[8]:= Chop[g2 /. First[sols]] Out[8]= {0} So we certianly do have solutions, even an infinte set of solutions, but none of them correspond to the same values of s and t. I am not sure if that is what you wanted or not. Andrzej Kozlowski === Subject: Re: Intersection of 2D Surfaces in 3D > Following is an example (slightly altered) given in intersection of 2- > D curves with one real root. c1 = {x - (t^2 - 1), y - (s^3 + s - 4) }; > c2 = {x - (s^2 + s + 5), y - (t^2 + 7 t - 2) }; It uses NSolve[Join[c1, c2], {x, y}, {s, t}] for supplying real roots > of 2D curves in 2D itself. Next, how to generalize further to Solve and find real intersection > curves of two parameter surfaces in 3-D by extending the same > Mathematica Join procedure? And how to Show the one parameter 3D space curve of intersection so > obtained ? The following attempt of course fails. c3 = {x - (t^2 - 1), y - (s^3 + s - 4), z - (t + s)}; > c4 = {x - (s^2 + s + 5), y - (t^2 + 7 t - 2),z -( t + s^2/2)}; > NSolve[Join[c3, c4], {x, y, z}, {t,s}]; FindRoot also was not successful. Narasimham Your two surfaces do not interesect: In[58]:= GroebnerBasis[Join[c3, c4], {x, y, s, t}] Out[58]= {1} So what do you mena by fails? What would constitute a success here? Andrzek Kozlowski === Subject: Intersection of 2D Surfaces in 3D Following is an example (slightly altered) given in intersection of 2- D curves with one real root. c1 = {x - (t^2 - 1), y - (s^3 + s - 4) }; c2 = {x - (s^2 + s + 5), y - (t^2 + 7 t - 2) }; It uses NSolve[Join[c1, c2], {x, y}, {s, t}] for supplying real roots of 2D curves in 2D itself. Next, how to generalize further to Solve and find real intersection curves of two parameter surfaces in 3-D by extending the same Mathematica Join procedure? And how to Show the one parameter 3D space curve of intersection so obtained ? The following attempt of course fails. c3 = {x - (t^2 - 1), y - (s^3 + s - 4), z - (t + s)}; c4 = {x - (s^2 + s + 5), y - (t^2 + 7 t - 2),z -( t + s^2/2)}; NSolve[Join[c3, c4], {x, y, z}, {t,s}]; FindRoot also was not successful. Narasimham === Subject: Re: Intersection of 2D Surfaces in 3D > Following is an example (slightly altered) given in intersection of 2- > D curves with one real root. c1 = {x - (t^2 - 1), y - (s^3 + s - 4) }; > c2 = {x - (s^2 + s + 5), y - (t^2 + 7 t - 2) }; It uses NSolve[Join[c1, c2], {x, y}, {s, t}] for supplying real roots > of 2D curves in 2D itself. Just a side note, but NSolve returns real and complex solutions. To get only the real roots, you could use DeleteCases as in c1 = {x - (t^2 - 1), y - (s^3 + s - 4)}; c2 = {x - (s^2 + s + 5), y - (t^2 + 7 t - 2)}; NSolve[Join[c1, c2], {x, y}, {s, t}] sol2d = DeleteCases[%, {rx_, ry_} /; ==> {{x -> 23.8213, y -> 57.6959}, {x -> 6.95079, y -> -13.7872}, {x -> 1.79728- 5.72439 [ImaginaryI], y -> -14.1904 + 3.63314 [ImaginaryI]}, {x -> 1.79728+ 5.72439 [ImaginaryI], y -> -14.1904 - 3.63314 [ImaginaryI]}, {x -> -0.183302 + 1.17396 [ImaginaryI], y -> 6.23603+ 5.05059 [ImaginaryI]}, {x -> -0.183302 - 1.17396 [ImaginaryI], y -> 6.23603- 5.05059 [ImaginaryI]}} ==> {{x -> 23.8213, y -> 57.6959}, {x -> 6.95079, y -> -13.7872}} > Next, how to generalize further to Solve and find real intersection > curves of two parameter surfaces in 3-D by extending the same > Mathematica Join procedure? And how to Show the one parameter 3D space curve of intersection so > obtained ? The following attempt of course fails. c3 = {x - (t^2 - 1), y - (s^3 + s - 4), z - (t + s)}; > c4 = {x - (s^2 + s + 5), y - (t^2 + 7 t - 2),z -( t + s^2/2)}; > NSolve[Join[c3, c4], {x, y, z}, {t,s}]; FindRoot also was not successful. NSolve returns an empty list as solution whenever it cannot find any solution. If you are confident that a solution exists, you should check that you have entered the correct equations. For the given c3 and c4, it seems that the parameters t and s cannot be eliminated. c3 = {x - (t^2 - 1), y - (s^3 + s - 4), z - (t + s)}; c4 = {x - (s^2 + s + 5), y - (t^2 + 7 t - 2), z - (t + s^2/2)}; NSolve[Join[c3, c4], {x, y, z}, {t, s}] (* ==> {} Empty list, i.e. no solution *) Eliminate[Thread[Equal[Join[c3, c4], 0]], {t, s}] == > False On the other hand, t and s can be eliminated from c1 ans c2: Eliminate[Thread[Equal[Join[c1, c2], 0]], {t, s}] ==> 1263970226 x == 7211108146 - 477420376 y - 28270737 y^2 + 10027446 y^3 + 564196 y^4 - 12565 y^5 && 68224 y + 110735 y^2 - 10210 y^3 - 1569 y^4 - 28 y^5 + y^6 == 10991228 Hope this helps, -- === Subject: Re: Limit[(x - Log[Cosh[x]]) SinIntegral[x], x -> Infinity] > I confirm the precise behavior you described. It's surprising that a > restart was required. Actually a ClearSystemCache[] is enough, but since cached results can affect the success of calculations, probably it would be better if Mathematica did not cache the result that it *cannot* calculate something. In[4]:= ClearSystemCache[] In[5]:= Limit[(x - Log[Cosh[x]]) SinIntegral[x], x -> Infinity] Out[5]= Limit[(x - Log[Cosh[x]]) SinIntegral[x], x -> Infinity] In[6]:= Limit[FullSimplify[(x - Log[Cosh[x]]) SinIntegral[x], x > 0], > x -> Infinity] Out[6]= (1/2)*Pi*Log[2] Note that using FullSimplify merely changes -Log[Cosh[x]] to +Log[Sech[x]], > but curiously, that seems to help. Hmm, this does not work for me: In[1]:= Limit[FullSimplify[(x - Log[Cosh[x]])*SinIntegral[x], x > 0], x -> Infinity] Out[1]= Limit[(x + Log[Sech[x]])*SinIntegral[x], x -> Infinity] I get back the same expression even if I evaluate all 6 input cells in turn. In[2]:= $Version Out[2]= 6.0 for Microsoft Windows (32-bit) (February 7, 2008) Szabolcs === Subject: Limit[(x - Log[Cosh[x]]) SinIntegral[x], x -> Infinity] I expected that Limit would try to compute the limit of terms in a product separately. Perhaps this is not feasible because of the large number of possible combinations? In the following example it can give result for the terms separately, but not for the product: In[1]:= Limit[(x - Log[Cosh[x]])*SinIntegral[x], x -> Infinity] Out[1]= Limit[(x - Log[Cosh[x]])*SinIntegral[x], x -> Infinity] In[2]:= Limit[x - Log[Cosh[x]], x -> Infinity] Out[2]= Log[2] In[3]:= Limit[SinIntegral[x], x -> Infinity] Out[3]= Pi/2 In[4]:= Limit[(x - Log[Cosh[x]])*SinIntegral[x], x -> Infinity] Out[4]= Limit[(x - Log[Cosh[x]])*SinIntegral[x], x -> Infinity] (Note that In[4] still didn't give a result.) However, if the evaluations are done in a different order (after a kernel restart), it is able to compute the result: In[1]:= Limit[x - Log[Cosh[x]], x -> Infinity] Out[1]= Log[2] In[2]:= Limit[SinIntegral[x], x -> Infinity] Out[2]= Pi/2 In[3]:= Limit[(x - Log[Cosh[x]])*SinIntegral[x], x -> Infinity] Out[3]= (1/2)*Pi*Log[2] Are there any options (perhaps SystemOptions) that would allow Limit to give an answer directly for the product of the terms? === Subject: Re: Limit[(x - Log[Cosh[x]]) SinIntegral[x], x -> Infinity] > I expected that Limit would try to compute the limit of terms in a > product separately. Perhaps this is not feasible because of the large > number of possible combinations? In the following example it can give result for the terms separately, > but not for the product: In[1]:= Limit[(x - Log[Cosh[x]])*SinIntegral[x], x -> Infinity] > Out[1]= Limit[(x - Log[Cosh[x]])*SinIntegral[x], x -> Infinity] In[2]:= Limit[x - Log[Cosh[x]], x -> Infinity] > Out[2]= Log[2] In[3]:= Limit[SinIntegral[x], x -> Infinity] > Out[3]= Pi/2 In[4]:= Limit[(x - Log[Cosh[x]])*SinIntegral[x], x -> Infinity] > Out[4]= Limit[(x - Log[Cosh[x]])*SinIntegral[x], x -> Infinity] (Note that In[4] still didn't give a result.) However, if the evaluations are done in a different order (after a > kernel restart), it is able to compute the result: In[1]:= Limit[x - Log[Cosh[x]], x -> Infinity] > Out[1]= Log[2] In[2]:= Limit[SinIntegral[x], x -> Infinity] > Out[2]= Pi/2 In[3]:= Limit[(x - Log[Cosh[x]])*SinIntegral[x], x -> Infinity] > Out[3]= (1/2)*Pi*Log[2] I confirm the precise behavior you described. It's surprising that a restart was required. > Are there any options (perhaps SystemOptions) that would allow Limit to > give an answer directly for the product of the terms? In[4]:= ClearSystemCache[] In[5]:= Limit[(x - Log[Cosh[x]]) SinIntegral[x], x -> Infinity] Out[5]= Limit[(x - Log[Cosh[x]]) SinIntegral[x], x -> Infinity] In[6]:= Limit[FullSimplify[(x - Log[Cosh[x]]) SinIntegral[x], x > 0], x -> Infinity] Out[6]= (1/2)*Pi*Log[2] Note that using FullSimplify merely changes -Log[Cosh[x]] to +Log[Sech[x]], but curiously, that seems to help. David === Subject: Re: Tagged list processing >This is related to a recent question. Best stated through an example. >>I have two flat lists of equal length: >>tag={0,0,1,0,0, -3,0,0,0,0, 2,4,1,0,0}; >>val={0,0,4,5,6, P,1/2,0,-3.0,a+4, 8,16.4,0,Sin[ang],Cos[ang]}; >>tag contains only integers whereas val can have numbers or >>expressions that will (eventually) evaluate to a number. >>Task. Generate a pointer list to all nz values in tag, and a >>corresponding list of values: >>nztag={3,6,11,12,13}; (* may be empty *) >>nzval={4,P,8,16.4,0}; (* may be empty *) >>and also build the complementary lists >>ztag={1,2,4,5,7,8,9,10,14,15}; >>zval={0,0,5,6,1/2,0,-3.0,a+4, Sin[ang],Cos[ang]}; >>Obviously ztag=Position[tag,0]; but which >>form argument do I use for nztag in Position[tag,form]? >>Can I build zval and nzval with Table for speed ? >>(lists may contain 10^4 to 10^6 items) >>Constraint: must work in 4.0 thru 6.0 since some of my > [...] This will work in version 4, and is significantly faster than what I posted before. tagsAndValues2[tag_List,val_List] := Module[ {ztag,nztag}, {nztag,ztag} = Transpose[Table[If[tag[[j]]==0, {Sequence[],j}, {j,Sequence[]}], {j,Length[tag]}]] {nztag,val[[nztag]],ztag,val[[ztag]]} ] Daniel Lichtblau Wolfram Research === Subject: Re: Tagged list processing > This is related to a recent question. Best stated through an example. > I have two flat lists of equal length: tag={0,0,1,0,0, -3,0,0,0,0, 2,4,1,0,0}; > val={0,0,4,5,6, P,1/2,0,-3.0,a+4, 8,16.4,0,Sin[ang],Cos[ang]}; tag contains only integers whereas val can have numbers or > expressions that will (eventually) evaluate to a number. Task. Generate a pointer list to all nz values in tag, and a > corresponding list of values: nztag={3,6,11,12,13}; (* may be empty *) > nzval={4,P,8,16.4,0}; (* may be empty *) and also build the complementary lists ztag={1,2,4,5,7,8,9,10,14,15}; > zval={0,0,5,6,1/2,0,-3.0,a+4, Sin[ang],Cos[ang]}; Obviously ztag=Position[tag,0]; but which > form argument do I use for nztag in Position[tag,form]? > Can I build zval and nzval with Table for speed ? > (lists may contain 10^4 to 10^6 items) Constraint: must work in 4.0 thru 6.0 since some of my This should work in all versions of Mathematica: tag = {0, 0, 1, 0, 0, -3, 0, 0, 0, 0, 2, 4, 1, 0, 0}; val = {0, 0, 4, 5, 6, P, 1/2, 0, -3.0, a + 4, 8, 16.4, 0, Sin[ang], Cos[ang]}; nztag = Position[tag, z_ /; z != 0] {{3}, {6}, {11}, {12}, {13}} nzval = Extract[val, nztag] {4, P, 8, 16.4, 0} etc. Andrzej Kozlowski === Subject: Re: Tagged list processing > This is related to a recent question. Best stated through an example. > I have two flat lists of equal length: tag={0,0,1,0,0, -3,0,0,0,0, 2,4,1,0,0}; > val={0,0,4,5,6, P,1/2,0,-3.0,a+4, 8,16.4,0,Sin[ang],Cos[ang]}; tag contains only integers whereas val can have numbers or > expressions that will (eventually) evaluate to a number. Task. Generate a pointer list to all nz values in tag, and a > corresponding list of values: nztag={3,6,11,12,13}; (* may be empty *) > nzval={4,P,8,16.4,0}; (* may be empty *) and also build the complementary lists ztag={1,2,4,5,7,8,9,10,14,15}; > zval={0,0,5,6,1/2,0,-3.0,a+4, Sin[ang],Cos[ang]}; Obviously ztag=Position[tag,0]; but which > form argument do I use for nztag in Position[tag,form]? > Can I build zval and nzval with Table for speed ? > (lists may contain 10^4 to 10^6 items) Constraint: must work in 4.0 thru 6.0 since some of my Here are some newbie approaches: First I would create a combined list with Inner: In[4]:=tagval = Inner[List, tag, val, List] Then, you can get nztag for example with Condition: > In[13]:= > Flatten[Position[tagval, > {a_, b_} /; a != 0]] > Out[13]= > {3, 6, 11, 12, 13} With the best, J=E1nos -------------------------------------------------------- The more money has to be spent to fix a problem, the more likely it is that the people with the money will agree to fix it. /Alex Satrapa/ === Subject: Re: Tagged list processing > This is related to a recent question. Best stated through an example. > I have two flat lists of equal length: tag={0,0,1,0,0, -3,0,0,0,0, 2,4,1,0,0}; > val={0,0,4,5,6, P,1/2,0,-3.0,a+4, 8,16.4,0,Sin[ang],Cos[ang]}; tag contains only integers whereas val can have numbers or > expressions that will (eventually) evaluate to a number. Task. Generate a pointer list to all nz values in tag, and a > corresponding list of values: nztag={3,6,11,12,13}; (* may be empty *) > nzval={4,P,8,16.4,0}; (* may be empty *) and also build the complementary lists ztag={1,2,4,5,7,8,9,10,14,15}; > zval={0,0,5,6,1/2,0,-3.0,a+4, Sin[ang],Cos[ang]}; Obviously ztag=Position[tag,0]; but which > form argument do I use for nztag in Position[tag,form]? > Can I build zval and nzval with Table for speed ? > (lists may contain 10^4 to 10^6 items) Constraint: must work in 4.0 thru 6.0 since some of my This will work for versions 5.0 through present, but not in 4.x. tagsAndValues[tag_List,val_List] := Module[ {n=Length[tag]}, Map[First,Reap[Do[If[tag[[j]]==0, Sow[j,ztag]; Sow[val[[j]],zval], Sow[j,nztag]; Sow[val[[j]],nzval]] , {j,n}], {nztag,nzval,ztag,zval}][[2]]] ] Example: {nztag,nzval,ztag,zval} = tagsAndValues[tag,val] In[4]:= InputForm[ {nztag,nzval,ztag,zval} = tagsAndValues[tag,val]] Out[4]//InputForm= {{3, 6, 11, 12, 13}, {4, P, 8, 16.4, 0}, {1, 2, 4, 5, 7, 8, 9, 10, 14, 15}, {0, 0, 5, 6, 1/2, 0, -3., 4 + a, Sin[ang], Cos[ang]}} For prior versions I'd suggest either using Position, or else emulating Sow/Reap using DownValue assignment. Other approaches will likely be noticeably slow, for lists in the size range you require. Daniel Lichtblau Wolfram Research === Subject: Tagged list processing This is related to a recent question. Best stated through an example. I have two flat lists of equal length: tag={0,0,1,0,0, -3,0,0,0,0, 2,4,1,0,0}; val={0,0,4,5,6, P,1/2,0,-3.0,a+4, 8,16.4,0,Sin[ang],Cos[ang]}; tag contains only integers whereas val can have numbers or expressions that will (eventually) evaluate to a number. Task. Generate a pointer list to all nz values in tag, and a corresponding list of values: nztag={3,6,11,12,13}; (* may be empty *) nzval={4,P,8,16.4,0}; (* may be empty *) and also build the complementary lists ztag={1,2,4,5,7,8,9,10,14,15}; zval={0,0,5,6,1/2,0,-3.0,a+4, Sin[ang],Cos[ang]}; Obviously ztag=Position[tag,0]; but which form argument do I use for nztag in Position[tag,form]? Can I build zval and nzval with Table for speed ? (lists may contain 10^4 to 10^6 items) Constraint: must work in 4.0 thru 6.0 since some of my === Subject: Re: Tagged list processing > This is related to a recent question. Best stated through an example. > I have two flat lists of equal length: tag={0,0,1,0,0, -3,0,0,0,0, 2,4,1,0,0}; > val={0,0,4,5,6, P,1/2,0,-3.0,a+4, 8,16.4,0,Sin[ang],Cos[ang]}; tag contains only integers whereas val can have numbers or > expressions that will (eventually) evaluate to a number. Task. Generate a pointer list to all nz values in tag, and a > corresponding list of values: nztag={3,6,11,12,13}; (* may be empty *) > nzval={4,P,8,16.4,0}; (* may be empty *) and also build the complementary lists ztag={1,2,4,5,7,8,9,10,14,15}; > zval={0,0,5,6,1/2,0,-3.0,a+4, Sin[ang],Cos[ang]}; Obviously ztag=Position[tag,0]; but which > form argument do I use for nztag in Position[tag,form]? > Can I build zval and nzval with Table for speed ? > (lists may contain 10^4 to 10^6 items) Constraint: must work in 4.0 thru 6.0 since some of my How about this? nztag = Flatten[Position[tag, x_ /; Abs[x] > 0]] nzval = val[[nztag]] ztag = Flatten[Position[tag, 0]] zval = val[[ztag]] Hope this helps, Mike === Subject: Re: Tagged list processing > This is related to a recent question. Best stated through an example. > I have two flat lists of equal length: tag={0,0,1,0,0, -3,0,0,0,0, 2,4,1,0,0}; > val={0,0,4,5,6, P,1/2,0,-3.0,a+4, 8,16.4,0,Sin[ang],Cos[ang]}; tag contains only integers whereas val can have numbers or > expressions that will (eventually) evaluate to a number. Task. Generate a pointer list to all nz values in tag, and a > corresponding list of values: nztag={3,6,11,12,13}; (* may be empty *) > nzval={4,P,8,16.4,0}; (* may be empty *) and also build the complementary lists ztag={1,2,4,5,7,8,9,10,14,15}; > zval={0,0,5,6,1/2,0,-3.0,a+4, Sin[ang],Cos[ang]}; Obviously ztag=Position[tag,0]; but which > form argument do I use for nztag in Position[tag,form]? > Can I build zval and nzval with Table for speed ? > (lists may contain 10^4 to 10^6 items) Constraint: must work in 4.0 thru 6.0 since some of my The following approach should work with version 4.0 and above (I have discarded a fastest solution that used Pick). On my system, it yields the four lists in less than 0.2 seconds, starting with two lists of 150,000 elements each. In[1]:= tag = {0, 0, 1, 0, 0, -3, 0, 0, 0, 0, 2, 4, 1, 0, 0}; val = {0, 0, 4, 5, 6, P, 1/2, 0, -3.0, a + 4, 8, 16.4, 0, Sin[ang], Cos[ang]}; In[3]:= ztag = Flatten@Position[tag, 0] Out[3]= {1, 2, 4, 5, 7, 8, 9, 10, 14, 15} In[4]:= nztag = Complement[Range[Length@tag], ztag] Out[4]= {3, 6, 11, 12, 13} In[5]:= (* Alternatively, though slower than above *) nztag = Flatten@Position[tag, x_ /; x != 0] Out[5]= {3, 6, 11, 12, 13} In[6]:= nzval = val[[nztag]] Out[6]= {4, P, 8, 16.4, 0} In[7]:= zval = val[[ztag]] Out[7]= {0, 0, 5, 6, 1/2, 0, -3., 4 + a, Sin[ang], Cos[ang]} In[8]:= tag = Flatten@Table[tag, {10^4}]; val = Flatten@Table[val, {10^4}]; In[10]:= First@Timing[ztag = Flatten@Position[tag, 0]] Out[10]= 0.149143 In[11]:= First@Timing[nztag = Complement[Range[Length@tag], ztag]] Out[11]= 0.043276 In[12]:= First@Timing[nzval = val[[nztag]]] Out[12]= 0.004319 In[13]:= First@Timing[zval = val[[ztag]]] Out[13]= 0.011485 In[14]:= %%%% + %%% + %% + % Out[14]= 0.208223 In[15]:= Length@tag Out[15]= 150000 -- === Subject: Re: x -> Starting with a fresh kernel. $Version 6.0 for Mac OS X x86 (64-bit) (March 13, 2008) Limit[#, x -> Infinity] & /@ ((x - Log[Cosh[x]])*SinIntegral[x]) (1/2)*Pi*Log[2] I also get this result after calculating the individual intermediate result= s in either order (fresh kernel in each case). Bob Hanlon > I expected that Limit would try to compute the limit of terms in a > product separately. Perhaps this is not feasible because of the large > number of possible combinations? In the following example it can give result for the terms separately, > but not for the product: In[1]:= Limit[(x - Log[Cosh[x]])*SinIntegral[x], x -> Infinity] > Out[1]= Limit[(x - Log[Cosh[x]])*SinIntegral[x], x -> Infinity] In[2]:= Limit[x - Log[Cosh[x]], x -> Infinity] > Out[2]= Log[2] In[3]:= Limit[SinIntegral[x], x -> Infinity] > Out[3]= Pi/2 In[4]:= Limit[(x - Log[Cosh[x]])*SinIntegral[x], x -> Infinity] > Out[4]= Limit[(x - Log[Cosh[x]])*SinIntegral[x], x -> Infinity] (Note that In[4] still didn't give a result.) However, if the evaluations are done in a different order (after a > kernel restart), it is able to compute the result: In[1]:= Limit[x - Log[Cosh[x]], x -> Infinity] > Out[1]= Log[2] In[2]:= Limit[SinIntegral[x], x -> Infinity] > Out[2]= Pi/2 In[3]:= Limit[(x - Log[Cosh[x]])*SinIntegral[x], x -> Infinity] > Out[3]= (1/2)*Pi*Log[2] > Are there any options (perhaps SystemOptions) that would allow Limit to= > give an answer directly for the product of the terms? > === Subject: symbolic evaluation I'm using Mathematica 5.1 I want to evaluate a simple equation symbolically, such as 7x = 14. of course the answer should be x = 14/7. I can't find a clear example on how to do this with a simple equation. Can anyone help me? TIA Paul === Subject: Re: symbolic evaluation Paul, If you are going to use Mathematica much, you should consider taking some time to review the basic commands in Mathematica. In this case you can just use Solve (Look it up in Help). Solve[7x==14] {{x->2}} The solutions always come in the form of rules, with arrows, that you can use to substitute x in any expression that contains x. The brackets are there because in general there may be multiple variables and multiple solutions. You could get rid of the brackets by: xsol = Part[Solve[7 x == 14], 1, 1] x -> 2 You could then use the rule, saved in xsol, to substitute in any expression, such as: x^2 + 3 x - 5 /. xsol 5 In the case of a simple equation like this there is another method of solving. We write the equation and then divide each side of the equation by 7 using a pure function (look up Function in Help and note how a slot notation for pure functions work. '#/7&' is the pure function. In the following we are also using '/@' to Map the function to each side of the equation. '%' is the previous output. Look up Map in Help.) 7 x == 14 #/7 & /@ % giving 7 x == 14 x == 2 -- David Park djmpark@comcast.net http://home.comcast.net/~djmpark/ > I'm using Mathematica 5.1 I want to evaluate a simple equation > symbolically, such as 7x = 14. of course the answer should be x = 14/7. > I can't find a clear example on how to do this with a simple equation. > Can anyone help me? > TIA > Paul > === Subject: Re: symbolic evaluation Did you really spend any time examining the documentation for Mathematica to learn the basics? It doesn't make sense to say evaluate the equation. Surely you want to solve it, for x. So why not look up Solve in the documentation. And be sure to look up the difference between the equality sign for an equation, the double-equal symbol ==, on the one hand, and the assignment (Set) single-equal symbol =, on the other hand. > I'm using Mathematica 5.1 I want to evaluate a simple equation > symbolically, such as 7x = 14. of course the answer should be x = 14/7. > I can't find a clear example on how to do this with a simple equation. > Can anyone help me? > TIA > Paul > -- Murray Eisenberg murray@math.umass.edu Mathematics & Statistics Dept. Lederle Graduate Research Tower phone 413 549-1020 (H) University of Massachusetts 413 545-2859 (W) 710 North Pleasant Street fax 413 545-1801 Amherst, MA 01003-9305 === Subject: Re: symbolic evaluation > I'm using Mathematica 5.1 I want to evaluate a simple equation > symbolically, such as 7x = 14. of course the answer should be x = 14/7. > I can't find a clear example on how to do this with a simple equation. > Can anyone help me? > TIA > Paul > You will be glad to know that Mathematica can solve complicated equations of this sort: Solve[7 x == 14] (Note the double equals sign) David Bailey http://www.dbaileyconsultancy.co.uk === Subject: Re: symbolic evaluation > I'm using Mathematica 5.1 I want to evaluate a simple equation > symbolically, such as 7x = 14. of course the answer should be x = > 14/7. > I can't find a clear example on how to do this with a simple equation. > Can anyone help me? x/.Solve[7 x==14,x] As for where that expression came from I suggest looking up the component pieces (starting with Solve) in the help documentation. Ssezi === Subject: Re: symbolic evaluation > I'm using Mathematica 5.1 I want to evaluate a simple equation > symbolically, such as 7x = 14. of course the answer should be x = 14/7. > I can't find a clear example on how to do this with a simple equation. I am not sure whether the issue is about keeping the rational number 14/7 in its unsimplified form (Mathematica will simplify it automatically to two). If this is the case, you could use HoldForm (at least for simple expression). For instance, In[1]:= Reduce[7 x == HoldForm@14] Out[1]= 14 x == -- 7 Otherwise, you can just use Reduce, Solve, or even Simplify as in the following examples. In[2]:= Reduce[7 x == 14] Out[2]= x == 2 In[3]:= Solve[7 x == 14] Out[3]= {{x -> 2}} In[4]:= Simplify[7 x == 14] Out[4]= x == 2 -- === Subject: Re: symbolic evaluation > I'm using Mathematica 5.1 I want to evaluate a simple equation > symbolically, such as 7x = 14. of course the answer should be x = 14/7. > I can't find a clear example on how to do this with a simple equation. > Can anyone help me? > TIA > Paul You mean you want to *solve* the equation, so search for solve in the docs. Also, there is a link called Equation solving on the startpage of the doc centre. === Subject: Re: symbolic evaluation x /. Solve[ 7*x==14,x][[1]] ?? > I'm using Mathematica 5.1 I want to evaluate a simple equation > symbolically, such as 7x = 14. of course the answer should be x = 14/7. > I can't find a clear example on how to do this with a simple equation. > Can anyone help me? > TIA > Paul > === Subject: The FinancialData Function Can anyone tell me where I can get more information about the data sources for Mathematica's new function FinancialData? Gregory === Subject: Re: The FinancialData Function See here FAQ http://support.wolfram.com/mathematica/paclets/financialdataqanda.en.html > Can anyone tell me where I can get more information about the data > sources for Mathematica's new function FinancialData? > Gregory > === Subject: FindMinimum[Print[]] Hello list ! I'm really new to Mathematica (though I can already say wow), and, following the tutorial[1] (which might be quite outdated), one of the exercise got me in trouble. The author asks to reformulate the following actions m = {{12, 1 + x, 4 - x, x}, {4 - x, 11, 1 + x, x}, {1 + x, 1 - x, 15, x}, {x - 1, x - 1, x - 1, x - 1}}; expr = Max[Re[Eigenvalues[m]]]; FindMinimum[expr, {x, 0, 1}] into a more optimized version. In the course of doing that, I wanted to do something like FindMinimum[Print[x]; x^2, {x, 1}], hoping to see how is this whole thing is expanded/parsed. But, despite didn't print the iterations as expected. I wanted to understand how I should write FindMinimum[Max[Eigenvalues[m]], {x, 0, 1}] so that the eigenvalues are computed on the fully numerical (non-symbolic) matrix. Footnotes: [1] http://library.wolfram.com/conferences/devconf99/withoff/ =2D- | Micha=EBl `Micha' Cadilhac | Isn't vi that text editor with = | | http://michael.cadilhac.name | two modes... One that beeps and = | | JID/MSN: | one that corrupts your file? = | `---- michael.cadilhac@gmail.com | -- Dan Jacobson - = --' === Subject: Re: FindMinimum[Print[]] > Hello list ! I'm really new to Mathematica (though I can already say wow), and, > following the tutorial[1] (which might be quite outdated), one of the > exercise got me in trouble. The author asks to reformulate the following actions m = {{12, 1 + x, 4 - x, x}, > {4 - x, 11, 1 + x, x}, > {1 + x, 1 - x, 15, x}, > {x - 1, x - 1, x - 1, x - 1}}; > expr = Max[Re[Eigenvalues[m]]]; > FindMinimum[expr, {x, 0, 1}] into a more optimized version. In the course of doing that, I wanted > to do something like > FindMinimum[Print[x]; x^2, {x, 1}], > hoping to see how is this whole thing is expanded/parsed. But, despite > didn't print the iterations as expected. I wanted to understand how I should write > FindMinimum[Max[Eigenvalues[m]], {x, 0, 1}] > so that the eigenvalues are computed on the fully numerical > (non-symbolic) matrix. > Footnotes: > [1] http://library.wolfram.com/conferences/devconf99/withoff/ One solution is to define a function that only evaluates with numerical (not symbolic) arguments: expr[x_?NumericQ] := Max[Re[Eigenvalues[{{12, 1 + x, 4 - x, x}, {4 - x, 11, 1 + x, x}, {1 + x, 1 - x, 15, x}, {x - 1, x - 1, x - 1, x - 1}}]]] FindMinimum[expr[x], {x, 1}] You can use the same technique to print each x value while FindMinimum is working, or you could use the EvaluationMonitor option. === Subject: Re: FindMinimum[Print[]] > Hello list ! I'm really new to Mathematica (though I can already say wow), and, > following the tutorial[1] (which might be quite outdated), one of the > exercise got me in trouble. The author asks to reformulate the following actions m = {{12, 1 + x, 4 - x, x}, > {4 - x, 11, 1 + x, x}, > {1 + x, 1 - x, 15, x}, > {x - 1, x - 1, x - 1, x - 1}}; > expr = Max[Re[Eigenvalues[m]]]; > FindMinimum[expr, {x, 0, 1}] into a more optimized version. In the course of doing that, I wanted > to do something like > FindMinimum[Print[x]; x^2, {x, 1}], > hoping to see how is this whole thing is expanded/parsed. But, despite > didn't print the iterations as expected. I wanted to understand how I should write > FindMinimum[Max[Eigenvalues[m]], {x, 0, 1}] > so that the eigenvalues are computed on the fully numerical > (non-symbolic) matrix. > Footnotes: > [1] http://library.wolfram.com/conferences/devconf99/withoff/ =2D- > | Micha=EBl `Micha' Cadilhac | Isn't vi that text editor with = > | > | http://michael.cadilhac.name | two modes... One that beeps and = > | > | JID/MSN: | one that corrupts your file? = > | > `---- michael.cadilhac@gmail.com | -- Dan Jacobson - = > --' The reason that inserting a Print into the expression to be minimised can be found in the help for FindMinimum: FindMinimum first localizes the values of all variables, then evaluates f with the variables being symbolic, and then repeatedly evaluates the result numerically. It is that initial symbolic evaluation that strips out the Print command. Although there are ways of avoiding this, the easiest way to achieve what you want is to use: FindMinimum[x^2, {x, 1}, EvaluationMonitor :> Print[x]] Without giving away the solution to the original exercise, try executing the original sequence of operations one step at a time (split into separate cells), and look at the intermediate results! Yes, the only reasonable reaction to Mathematica is Wow! David Bailey http://www.dbaileyconsultancy.co.uk === Subject: Re: FindMinimum[Print[]] > I'm really new to Mathematica (though I can already say wow), and, > following the tutorial[1] (which might be quite outdated), one of the > exercise got me in trouble. The author asks to reformulate the following actions m = {{12, 1 + x, 4 - x, x}, > {4 - x, 11, 1 + x, x}, > {1 + x, 1 - x, 15, x}, > {x - 1, x - 1, x - 1, x - 1}}; > expr = Max[Re[Eigenvalues[m]]]; > FindMinimum[expr, {x, 0, 1}] into a more optimized version. In the course of doing that, I wanted > to do something like > FindMinimum[Print[x]; x^2, {x, 1}], > hoping to see how is this whole thing is expanded/parsed. But, despite > didn't print the iterations as expected. I wanted to understand how I should write > FindMinimum[Max[Eigenvalues[m]], {x, 0, 1}] > so that the eigenvalues are computed on the fully numerical > (non-symbolic) matrix. The option StepMonitor is what you are looking for. In[1]:= FindMinimum[Exp[x] + 1/x, {x, 1}, StepMonitor :> Print[Step to x = , x]] During evaluation of In[1]:= Step to x = 0.788886 During evaluation of In[1]:= Step to x = 0.677316 During evaluation of In[1]:= Step to x = 0.706578 During evaluation of In[1]:= Step to x = 0.703587 During evaluation of In[1]:= Step to x = 0.703467 During evaluation of In[1]:= Step to x = 0.703467 Out[1]= {3.44228, {x -> 0.703467}} In[2]:= m = {{12, 1 + x, 4 - x, x}, {4 - x, 11, 1 + x, x}, {1 + x, 1 - x, 15, x}, {x - 1, x - 1, x - 1, x - 1}}; expr = Max[Re[Eigenvalues[m]]]; FindMinimum[expr, {x, 0, 1}, StepMonitor :> Print[Step to x = , x]] During evaluation of In[2]:= Step to x = 0.362425 During evaluation of In[2]:= Step to x = 0.362425 During evaluation of In[2]:= Step to x = 0.362159 During evaluation of In[2]:= Step to x = 0.362151 Out[4]= {16.8343, {x -> 0.362151}} HTH, -- === Subject: Mathematica SIG (Washington DC Area) The Washington D.C. area Mathematica Special Interest Group will meet Friday, 28 March, 7:30 to 9:00 a.m. at the SAIC Enterprise Center building in Tysons Corner (see directions below). Early risers meet before 7:00 in the morning for admission at the front desk, then we have a Dutch treat breakfast downstairs. By about 7:30 we have moved to one of the projector rooms. Meetings consist of a prepared talk, informal discussion about Mathematica programming and applications, general questions, and new business. 1. Talks: In Group Theory and Confidence Intervals, Bruce Colletti uses group theory to build a confidence interval for the mean of a random variable that is symmetric about its mean but whose distribution is unknown. The underlying random sample need not be large. Mel Friedman will give a Mystery Presentation taken from: - Reading information into Mathematica from Excel - Using Mathematica to compute convolution and correlation integrals - Using Mathematica to compute Fourier Transforms - Using Mathematica to integrate numerically-defined functions - Using Mathematica for non-linear least squares Dan Martinez will showcase his dial programming hustle that demonstrates an analog depiction of multiple time-series data sets. What we'll see should be in our Mathematica repertoire. To inquire about attending, e-mail Dan Martinez (dmartinez@sprintmail.com) or Bruce Colletti (bcolletti@compuserve.com). In your e-mail subject line, please include 'Mathematica SIG.' A SIG representative will meet you in the lobby. Please arrive no later than ten minutes to seven if you wish to join us for breakfast, and no later than twenty after seven to attend the meeting only. The desk officer will ask for a driver's license before issuing a visitor's badge. === Subject: Wrapping text to fit a rectangle Is there a way of wrapping Text[] so that it fits inside a Rectangle{]?? Robert Prince-Wright Houston TX, 77006 USA _____ _ Never miss a thing. Make Yahoo your home page. http://www.yahoo.com/r/hs === Subject: Re: Wrapping text to fit a rectangle > Is there a way of wrapping Text[] so that it fits > inside a Rectangle{]?? Here's how I do it: Graphics[{ FaceForm[] , EdgeForm[Black] , Rectangle[{0, 0}, {300, 200}] , Inset[ Framed@Pane[ Style[ Wrapped text here.nLong enough to show wrapping. , Label , Bold , LineIndent -> 0 , TextAlignment -> Left] , 80] , {150, 0} , {Left, Bottom}] }] It's not pretty, but it lets me get control over the details. With Options for placement of the Pane contents, you can implement an attached Slider to scroll the text too. ScrollingWrappingPane[] would be a nice addition to the language. Be aware, though that Pane had Magnify issues until 6.0.2. I think TextCell can be made to work inside Inset too. Just differently. Hth, Fred Klingener === Subject: Re: Wrapping text to fit a rectangle > Is there a way of wrapping Text[] so that it fits > inside a Rectangle{]?? Does something like these fits your need? (Though I may not have correctly understood your question.) Graphics[{Rectangle[], Text[Style[x^2 + y^2 < 1, Large, Orange], {Center, Center}]}] Framed@Graphics[ Text[Style[x^2 + y^2 < 1, Large, Orange], {Center, Center}]] -- === Subject: Re: Wrapping text to fit a rectangle > Is there a way of wrapping Text[] so that it fits > inside a Rectangle{]?? Well, the following works, but I have no idea if it is the right way of doing this: Graphics[Inset@ TextCell[Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum., PageWidth -> 200]] === Subject: Re: Wrapping text to fit a rectangle it is not Text[] and not Rectangle[] but cc = Framed@(StringJoin @@ Table[The quick brown fox jump over the lazy dog. , {10}]); Graphics[ {Inset[cc, {0, 0}, {0, 0}, {400, 100}]} ] may do what you want. > Is there a way of wrapping Text[] so that it fits > inside a Rectangle{]?? Robert Prince-Wright > Houston > TX, 77006 > USA > _____ _ > Never miss a thing. Make Yahoo your home page. > http://www.yahoo.com/r/hs > === Subject: inverse of partitioned matrix I would like to find (symbolically) inverse of certain 3x3 matrices which are block partitioned. For example for 2x2 case the following solution is available http://www.cs.nthu.edu.tw/~jang/book/addenda/matinv/matinv/ However, I would like to find inverse of 3x3, and 4x4 block matrix A B C D F G H I J === Subject: Re: Equi-sized tick labels There is a bug in Mathematica graphics such that when one supplies one's= own > Tick specifications, the plot does not initially display the correct tic= k > lengths on the x-axis. But if you select the plot and resize it, then th= e x > ticks will snap to the specification. If you go with the Automatic Ticks= > then the problem does not occur. Indeed, I'm really sorry to have been so misled by this. Taking > another look at the figures that Mathematica is *exporting*, rather > than displaying, my code is clearly quite wrong. Just to revisit this quickly, the bug actually does exist but only when using both the CustomTicks and MathPSfrag packages to export the graphics. I'll have to take it up with their authors, but in the meantime something like the code I originally posted is quite useful to work around the problem if you are indeed using MathPSfrag. If you are not, it produces distort ticks, as I found. Explaining why I thought there was a problem and then got confused: the problem *did* occur in my test suite, but when I slimmed it down to post here I got rid of MathPSfrag, which removed the problem -- except that the display bug mentioned by David tricked me into thinking the problem was still there! Will === Subject: Re: Problems with differentiating Piecewise functions > If I set up a piecewise function and differentiate it: In[112]:= pw1 = Piecewise[{{x^2, x <= 0}, {x, x > 0}}] Out[112]= [Piecewise] { > {x^2, x <= 0}, > {x, x > 0} > } In[113]:= pw1 /. x -> 0 Out[113]= 0 In[114]:= pw1d = D[pw1, x] Out[114]= [Piecewise] { > {2 x, x < 0}, > {1, x > 0}, > {Indeterminate, !(* > TagBox[True, > PiecewiseDefault, > AutoDelete->False, > DeletionWarning->True])} > } In[115]:= pw1d /. x -> 0 Out[115]= Indeterminate Then at the joins between the pieces I get Indeterminate values, > because the limit x <= 0 has become x < 0 after differentiation. Does > anyone know a solution to this problem? > Howard. > What do you mean by a solution to this problem? You have a function that is not differentiable at 0 and you would like it's derivative to have a value there? You can't expect a solution to a problem when you do not tell us what is the problem (except the fact that not all functions are differentiable - but that's life). Note that is your pieceise function is actually differentiable than the derivative is defined everywhere: pw2 = Piecewise[{{x^2, x <= 0}, {x^3, x > 0}}]; pw2d = D[pw2, x] Piecewise[{{2*x, x < 0}, {0, x == 0}}, 3*x^2] This is also as it should be. What else would you expect? Andrzej Kozlowski === Subject: Re: Problems with differentiating Piecewise functions >> If I set up a piecewise function and differentiate it: > In[112]:= pw1 = Piecewise[{{x^2, x <= 0}, {x, x > 0}}] > Out[112]= [Piecewise] { >> {x^2, x <= 0}, >> {x, x > 0} >> } > In[113]:= pw1 /. x -> 0 > Out[113]= 0 > In[114]:= pw1d = D[pw1, x] > Out[114]= [Piecewise] { >> {2 x, x < 0}, >> {1, x > 0}, >> {Indeterminate, !(* >> TagBox[True, >> PiecewiseDefault, >> AutoDelete->False, >> DeletionWarning->True])} >> } > In[115]:= pw1d /. x -> 0 > Out[115]= Indeterminate > Then at the joins between the pieces I get Indeterminate values, >> because the limit x <= 0 has become x < 0 after differentiation. >> Does >> anyone know a solution to this problem? >> Howard. What do you mean by a solution to this problem? You have a > function that is not differentiable at 0 and you would like it's > derivative to have a value there? You can't expect a solution to a > problem when you do not tell us what is the problem (except the > fact > that not all functions are differentiable - but that's life). > Note that is your pieceise function is actually differentiable than > the derivative is defined everywhere: pw2 = Piecewise[{{x^2, x <= 0}, {x^3, x > 0}}]; pw2d = D[pw2, x] > Piecewise[{{2*x, x < 0}, {0, x == 0}}, 3*x^2] This is also as it should be. What else would you expect? Andrzej Kozlowski >> example that I posted (I simplified my problem by cutting and pasting >> an example from the help file to keep the post short). I am actually >> fitting cubic splines and the functions are continuous up to the >> second derivative (at least to the accuracy of machine precision). A >> better example is: >> In[54]:= pw[x_] := >> Piecewise[{{0.+ 0.007508378277320685 x + 7.561460342471517*10^-7 x^3, >> x < 50}, {-4.8729206849430454*10^-6 (-125.76959597633721 + >> x) (1148.1044516606876- 47.50636365246156 x + x^2), 50 <= x}}] >> In[55]:= pw[x] >> Out[55]= [Piecewise] { >> {0.+ 0.00750838 x + 7.56146*10^-7 x^3, x < 50}, >> {-4.87292*10^-6 (-125.77 + x) (1148.1- 47.5064 x + x^2), 50 <= x} >> } >> In[56]:= pw[50] >> Out[56]= 0.469937 >> In[57]:= pw[50 + 10^-30] >> Out[57]= 0.469937 >> In[58]:= pw[50 - 10^-30] >> Out[58]= 0.469937 >> In[60]:= pw'[x] >> Out[60]= [Piecewise] { >> {0.00750838+ 2.26844*10^-6 x^2, x < 50}, >> {-4.87292*10^-6 (-125.77 + x) (-47.5064 + 2 x) - >> 4.87292*10^-6 (1148.1- 47.5064 x + x^2), x > 50}, >> {Indeterminate, !(* >> TagBox[True, >> PiecewiseDefault, >> AutoDelete->False, >> DeletionWarning->True])} >> } >> In[61]:= pw'[50] >> Out[61]= Indeterminate >> In[62]:= pw'[50 + 10^-30] >> Out[62]= 0.0131795 >> In[63]:= pw'[50 - 10^-30] >> Out[63]= 0.0131795 >> Also if you Plot pw or pw' you get an annoying gap in the plot at the >> join (but strangely not pw''). My guess is that Mathematica is too >> pedantic about machine precision and is treating each piece as an >> algebraic equation. However this does not explain why Plot behaves >> funnily and doesn't help if you are trying to do numerical analysis. You are violating one of the most fundamental principles of computer > algebra: do not mix approximate numbers with symbolic computation. > More correctly, such mixing requires a great deal of care and > symbolic algebraic techniques that can deal with approximate numbers > (and even more so with machine precision input) are still in their > infancy. (In fact Mathematica is one of the few systems that make it > to some extent possible). In your case the symbolic technique you > are using is differentiation of a piecewise function, and this > cannot be reliably combined with numerical precision input. The answer to your problem is simple. Switch from using a mixture of > symbolic methods and approximate input to a purely numeric setting. > The best way to do this, I think, is by using FunctionInterpolation. > So what you need to do is this: pw[x_] := > Piecewise[{{0. + 0.007508378277320685 x + 7.561460342471517*10^-7 x^3, > x < 50}, {-4.8729206849430454*10^-6 (-125.76959597633721 + > x) (1148.1044516606876 - 47.50636365246156 x + x^2), 50 <= x}}] f = FunctionInterpolation[pw[x], {x, 0, 80}]; Plot[f[x], {x, 40, 60}] shows a continuous curve Plot[f'[x], {x, 40, 60}] shows an almost smooth curve, with a slight kink at the break > point. One could probably play with the options to > FunctionInterpolation to smoothen it. Andrzej Kozlowski Actually, you can get a smooth looking derivative by using a higher interpolation order: f = FunctionInterpolation[pw[x], {x, 0, 80}, InterpolationOrder -> 10]; Plot[f'[x], {x, 40, 60}] looks very smooth and so does: Plot[f''[x], {x, 40, 60}] Andrzej Kozlowski === Subject: Re: Problems with differentiating Piecewise functions > If I set up a piecewise function and differentiate it: > In[112]:= pw1 = Piecewise[{{x^2, x <= 0}, {x, x > 0}}] > Out[112]= [Piecewise] { > {x^2, x <= 0}, > {x, x > 0} > } > In[113]:= pw1 /. x -> 0 > Out[113]= 0 > In[114]:= pw1d = D[pw1, x] > Out[114]= [Piecewise] { > {2 x, x < 0}, > {1, x > 0}, > {Indeterminate, !(* > TagBox[True, > PiecewiseDefault, > AutoDelete->False, > DeletionWarning->True])} > } > In[115]:= pw1d /. x -> 0 > Out[115]= Indeterminate > Then at the joins between the pieces I get Indeterminate values, > because the limit x <= 0 has become x < 0 after differentiation. > Does > anyone know a solution to this problem? > Howard. >> What do you mean by a solution to this problem? You have a >> function that is not differentiable at 0 and you would like it's >> derivative to have a value there? You can't expect a solution to a >> problem when you do not tell us what is the problem (except the fact >> that not all functions are differentiable - but that's life). >> Note that is your pieceise function is actually differentiable than >> the derivative is defined everywhere: >> pw2 = Piecewise[{{x^2, x <= 0}, {x^3, x > 0}}]; >> pw2d = D[pw2, x] >> Piecewise[{{2*x, x < 0}, {0, x == 0}}, 3*x^2] >> This is also as it should be. What else would you expect? >> Andrzej Kozlowski example that I posted (I simplified my problem by cutting and pasting > an example from the help file to keep the post short). I am actually > fitting cubic splines and the functions are continuous up to the > second derivative (at least to the accuracy of machine precision). A > better example is: In[54]:= pw[x_] := > Piecewise[{{0.+ 0.007508378277320685 x + 7.561460342471517*10^-7 x^3, > x < 50}, {-4.8729206849430454*10^-6 (-125.76959597633721 + > x) (1148.1044516606876- 47.50636365246156 x + x^2), 50 <= x}}] In[55]:= pw[x] Out[55]= [Piecewise] { > {0.+ 0.00750838 x + 7.56146*10^-7 x^3, x < 50}, > {-4.87292*10^-6 (-125.77 + x) (1148.1- 47.5064 x + x^2), 50 <= x} > } In[56]:= pw[50] Out[56]= 0.469937 In[57]:= pw[50 + 10^-30] Out[57]= 0.469937 In[58]:= pw[50 - 10^-30] Out[58]= 0.469937 In[60]:= pw'[x] Out[60]= [Piecewise] { > {0.00750838+ 2.26844*10^-6 x^2, x < 50}, > {-4.87292*10^-6 (-125.77 + x) (-47.5064 + 2 x) - > 4.87292*10^-6 (1148.1- 47.5064 x + x^2), x > 50}, > {Indeterminate, !(* > TagBox[True, > PiecewiseDefault, > AutoDelete->False, > DeletionWarning->True])} > } In[61]:= pw'[50] Out[61]= Indeterminate In[62]:= pw'[50 + 10^-30] Out[62]= 0.0131795 In[63]:= pw'[50 - 10^-30] Out[63]= 0.0131795 Also if you Plot pw or pw' you get an annoying gap in the plot at the > join (but strangely not pw''). My guess is that Mathematica is too > pedantic about machine precision and is treating each piece as an > algebraic equation. However this does not explain why Plot behaves > funnily and doesn't help if you are trying to do numerical analysis. > You are violating one of the most fundamental principles of computer algebra: do not mix approximate numbers with symbolic computation. More correctly, such mixing requires a great deal of care and symbolic algebraic techniques that can deal with approximate numbers (and even more so with machine precision input) are still in their infancy. (In fact Mathematica is one of the few systems that make it to some extent possible). In your case the symbolic technique you are using is differentiation of a piecewise function, and this cannot be reliably combined with numerical precision input. The answer to your problem is simple. Switch from using a mixture of symbolic methods and approximate input to a purely numeric setting. The best way to do this, I think, is by using FunctionInterpolation. So what you need to do is this: pw[x_] := Piecewise[{{0. + 0.007508378277320685 x + 7.561460342471517*10^-7 x^3, x < 50}, {-4.8729206849430454*10^-6 (-125.76959597633721 + x) (1148.1044516606876 - 47.50636365246156 x + x^2), 50 <= x}}] f = FunctionInterpolation[pw[x], {x, 0, 80}]; Plot[f[x], {x, 40, 60}] shows a continuous curve Plot[f'[x], {x, 40, 60}] shows an almost smooth curve, with a slight kink at the break point. One could probably play with the options to FunctionInterpolation to smoothen it. Andrzej Kozlowski === Subject: Re: Problems with differentiating Piecewise functions > If I set up a piecewise function and differentiate it: In[112]:= pw1 = Piecewise[{{x^2, x <= 0}, {x, x > 0}}] Out[112]= [Piecewise] { > {x^2, x <= 0}, > {x, x > 0} > } In[113]:= pw1 /. x -> 0 Out[113]= 0 In[114]:= pw1d = D[pw1, x] Out[114]= [Piecewise] { > {2 x, x < 0}, > {1, x > 0}, > {Indeterminate, !(* > TagBox[True, > PiecewiseDefault, > AutoDelete->False, > DeletionWarning->True])} > } In[115]:= pw1d /. x -> 0 Out[115]= Indeterminate Then at the joins between the pieces I get Indeterminate values, > because the limit x <= 0 has become x < 0 after differentiation. Does > anyone know a solution to this problem? > Howard. What do you mean by a solution to this problem? You have a > function that is not differentiable at 0 and you would like it's > derivative to have a value there? You can't expect a solution to a > problem when you do not tell us what is the problem (except the fact > that not all functions are differentiable - but that's life). > Note that is your pieceise function is actually differentiable than > the derivative is defined everywhere: pw2 = Piecewise[{{x^2, x <= 0}, {x^3, x > 0}}]; pw2d = D[pw2, x] > Piecewise[{{2*x, x < 0}, {0, x == 0}}, 3*x^2] This is also as it should be. What else would you expect? Andrzej Kozlowski example that I posted (I simplified my problem by cutting and pasting > an example from the help file to keep the post short). I am actually > fitting cubic splines and the functions are continuous up to the > second derivative (at least to the accuracy of machine precision). A > better example is: In[54]:= pw[x_] := > Piecewise[{{0.+ 0.007508378277320685 x + 7.561460342471517*10^-7 x^3, > x < 50}, {-4.8729206849430454*10^-6 (-125.76959597633721 + > x) (1148.1044516606876- 47.50636365246156 x + x^2), 50 <= x}}] In[55]:= pw[x] Out[55]= [Piecewise] { > {0.+ 0.00750838 x + 7.56146*10^-7 x^3, x < 50}, > {-4.87292*10^-6 (-125.77 + x) (1148.1- 47.5064 x + x^2), 50 <= x} > } In[56]:= pw[50] Out[56]= 0.469937 In[57]:= pw[50 + 10^-30] Out[57]= 0.469937 In[58]:= pw[50 - 10^-30] Out[58]= 0.469937 In[60]:= pw'[x] Out[60]= [Piecewise] { > {0.00750838+ 2.26844*10^-6 x^2, x < 50}, > {-4.87292*10^-6 (-125.77 + x) (-47.5064 + 2 x) - > 4.87292*10^-6 (1148.1- 47.5064 x + x^2), x > 50}, > {Indeterminate, !(* > TagBox[True, > PiecewiseDefault, > AutoDelete->False, > DeletionWarning->True])} > } In[61]:= pw'[50] Out[61]= Indeterminate In[62]:= pw'[50 + 10^-30] Out[62]= 0.0131795 In[63]:= pw'[50 - 10^-30] Out[63]= 0.0131795 Also if you Plot pw or pw' you get an annoying gap in the plot at the > join (but strangely not pw''). My guess is that Mathematica is too > pedantic about machine precision and is treating each piece as an > algebraic equation. However this does not explain why Plot behaves > funnily and doesn't help if you are trying to do numerical analysis. InterpolatingFunctions but I was really wanted to plot me exact equations and I am not sure exactly what InterpolatingFunctions do. Since I am fitting the splines I have equations for each piece of pw' and pw'' and I am manually making Piecewises for pw' and pw''. This works but isn't very elegant. As for the plotting I didn't know about the Exclude options, I will give this a try. === Subject: Re: Problems with differentiating Piecewise functions Very interesting. I don't know why this is happening. Note that if you plot the functions (derivatives up to and including pw'''[x]) with the ExclusionsStyle set, it shows that Mathematica thinks all of the functions have a gap. I recommend something like Plot[Derivative[2][pw][x], {x, 40, 60}, ExclusionsStyle -> {Thick, Red}, PlotStyle -> Thick] C.O. > If I set up a piecewise function and differentiate it: In[112]:= pw1 = Piecewise[{{x^2, x <= 0}, {x, x > 0}}] Out[112]= [Piecewise] { > {x^2, x <= 0}, > {x, x > 0} > } In[113]:= pw1 /. x -> 0 Out[113]= 0 In[114]:= pw1d = D[pw1, x] Out[114]= [Piecewise] { > {2 x, x < 0}, > {1, x > 0}, > {Indeterminate, !(* > TagBox[True, > PiecewiseDefault, > AutoDelete->False, > DeletionWarning->True])} > } In[115]:= pw1d /. x -> 0 Out[115]= Indeterminate Then at the joins between the pieces I get Indeterminate values, > because the limit x <= 0 has become x < 0 after differentiation. Does > anyone know a solution to this problem? > Howard. What do you mean by a solution to this problem? You have a > function that is not differentiable at 0 and you would like it's > derivative to have a value there? You can't expect a solution to a > problem when you do not tell us what is the problem (except the fact > that not all functions are differentiable - but that's life). > Note that is your pieceise function is actually differentiable than > the derivative is defined everywhere: pw2 = Piecewise[{{x^2, x <= 0}, {x^3, x > 0}}]; pw2d = D[pw2, x] > Piecewise[{{2*x, x < 0}, {0, x == 0}}, 3*x^2] This is also as it should be. What else would you expect? Andrzej Kozlowski example that I posted (I simplified my problem by cutting and pasting > an example from the help file to keep the post short). I am actually > fitting cubic splines and the functions are continuous up to the > second derivative (at least to the accuracy of machine precision). A > better example is: In[54]:= pw[x_] := > Piecewise[{{0.+ 0.007508378277320685 x + 7.561460342471517*10^-7 x^3, > x < 50}, {-4.8729206849430454*10^-6 (-125.76959597633721 + > x) (1148.1044516606876- 47.50636365246156 x + x^2), 50 <= x}}] In[55]:= pw[x] Out[55]= [Piecewise] { > {0.+ 0.00750838 x + 7.56146*10^-7 x^3, x < 50}, > {-4.87292*10^-6 (-125.77 + x) (1148.1- 47.5064 x + x^2), 50 <= x} > } In[56]:= pw[50] Out[56]= 0.469937 In[57]:= pw[50 + 10^-30] Out[57]= 0.469937 In[58]:= pw[50 - 10^-30] Out[58]= 0.469937 In[60]:= pw'[x] Out[60]= [Piecewise] { > {0.00750838+ 2.26844*10^-6 x^2, x < 50}, > {-4.87292*10^-6 (-125.77 + x) (-47.5064 + 2 x) - > 4.87292*10^-6 (1148.1- 47.5064 x + x^2), x > 50}, > {Indeterminate, !(* > TagBox[True, > PiecewiseDefault, > AutoDelete->False, > DeletionWarning->True])} > } In[61]:= pw'[50] Out[61]= Indeterminate In[62]:= pw'[50 + 10^-30] Out[62]= 0.0131795 In[63]:= pw'[50 - 10^-30] Out[63]= 0.0131795 Also if you Plot pw or pw' you get an annoying gap in the plot at the > join (but strangely not pw''). My guess is that Mathematica is too > pedantic about machine precision and is treating each piece as an > algebraic equation. However this does not explain why Plot behaves > funnily and doesn't help if you are trying to do numerical analysis. -- Curtis Osterhoudt cfo@remove_this.lanl.and_this.gov PGP Key ID: 0x4DCA2A10 Please avoid sending me Word or PowerPoint attachments See http://www.gnu.org/philosophy/no-word-attachments.html === Subject: Re: Problems with differentiating Piecewise functions >If I set up a piecewise function and differentiate it: > In[112]:= pw1 = Piecewise[{{x^2, x <= 0}, {x, x > 0}}] > Out[112]= [Piecewise] { > {x^2, x <= 0}, > {x, x > 0} >} > In[113]:= pw1 /. x -> 0 > Out[113]= 0 > In[114]:= pw1d = D[pw1, x] > Out[114]= [Piecewise] { > {2 x, x < 0}, > {1, x > 0}, > {Indeterminate, !(* > TagBox[True, > PiecewiseDefault, > AutoDelete->False, > DeletionWarning->True])} >} > In[115]:= pw1d /. x -> 0 > Out[115]= Indeterminate > Then at the joins between the pieces I get Indeterminate values, >because the limit x <= 0 has become x < 0 after differentiation. Does >anyone know a solution to this problem? > Howard. > > What do you mean by a solution to this problem? You have a >>function that is not differentiable at 0 and you would like it's >>derivative to have a value there? You can't expect a solution to a >>problem when you do not tell us what is the problem (except the fact >>that not all functions are differentiable - but that's life). >>Note that is your pieceise function is actually differentiable than >>the derivative is defined everywhere: >>pw2 = Piecewise[{{x^2, x <= 0}, {x^3, x > 0}}]; >>pw2d = D[pw2, x] >>Piecewise[{{2*x, x < 0}, {0, x == 0}}, 3*x^2] >>This is also as it should be. What else would you expect? >>Andrzej Kozlowski >> example that I posted (I simplified my problem by cutting and pasting >an example from the help file to keep the post short). I am actually >fitting cubic splines and the functions are continuous up to the >second derivative (at least to the accuracy of machine precision). A >better example is: In[54]:= pw[x_] := > Piecewise[{{0.+ 0.007508378277320685 x + 7.561460342471517*10^-7 x^3, > x < 50}, {-4.8729206849430454*10^-6 (-125.76959597633721 + > x) (1148.1044516606876- 47.50636365246156 x + x^2), 50 <= x}}] In[55]:= pw[x] Out[55]= [Piecewise] { > {0.+ 0.00750838 x + 7.56146*10^-7 x^3, x < 50}, > {-4.87292*10^-6 (-125.77 + x) (1148.1- 47.5064 x + x^2), 50 <= x} > } In[56]:= pw[50] Out[56]= 0.469937 In[57]:= pw[50 + 10^-30] Out[57]= 0.469937 In[58]:= pw[50 - 10^-30] Out[58]= 0.469937 In[60]:= pw'[x] Out[60]= [Piecewise] { > {0.00750838+ 2.26844*10^-6 x^2, x < 50}, > {-4.87292*10^-6 (-125.77 + x) (-47.5064 + 2 x) - > 4.87292*10^-6 (1148.1- 47.5064 x + x^2), x > 50}, > {Indeterminate, !(* > TagBox[True, > PiecewiseDefault, > AutoDelete->False, > DeletionWarning->True])} > } In[61]:= pw'[50] Out[61]= Indeterminate In[62]:= pw'[50 + 10^-30] Out[62]= 0.0131795 In[63]:= pw'[50 - 10^-30] Out[63]= 0.0131795 Also if you Plot pw or pw' you get an annoying gap in the plot at the >join (but strangely not pw''). My guess is that Mathematica is too >pedantic about machine precision and is treating each piece as an >algebraic equation. However this does not explain why Plot behaves >funnily and doesn't help if you are trying to do numerical analysis. > > One idea is to use Interpolation instead of Piecewise to creat your spline. If you know the derivatives at each of the control points, then the syntax to use is: Interpolation[{{{x0}, y0, dy0}, {{x1}, y1, dy1}, ...}, InterpolationOrder->3] For example, suppose we choose x0, x1, x2 to be 0, 50, 100, and obtain: spline = Interpolation[{{{0}, pw[0], pw'[0]}, {{50}, pw[50], pw'[49.99999]}, {{100}, pw[100], pw'[100]}}, InterpolationOrder->3] Of course, whatever method you used to create your spline should be able to generate derivatives at the control points, and you would use this data directly instead of creating pw first. spline[x], spline'[x] both plot nicely with no gaps. Carl Woll Wolfram Research === Subject: Re: Problems with differentiating Piecewise functions If I set up a piecewise function and differentiate it: In[112]:= pw1 = Piecewise[{{x^2, x <= 0}, {x, x > 0}}] Out[112]= [Piecewise] { > {x^2, x <= 0}, > {x, x > 0} > } In[113]:= pw1 /. x -> 0 Out[113]= 0 In[114]:= pw1d = D[pw1, x] Out[114]= [Piecewise] { > {2 x, x < 0}, > {1, x > 0}, > {Indeterminate, !(* > TagBox[True, > PiecewiseDefault, > AutoDelete->False, > DeletionWarning->True])} > } In[115]:= pw1d /. x -> 0 Out[115]= Indeterminate Then at the joins between the pieces I get Indeterminate values, > because the limit x <= 0 has become x < 0 after differentiation. Does > anyone know a solution to this problem? > Howard. What do you mean by a solution to this problem? You have a > function that is not differentiable at 0 and you would like it's > derivative to have a value there? You can't expect a solution to a > problem when you do not tell us what is the problem (except the fact > that not all functions are differentiable - but that's life). > Note that is your pieceise function is actually differentiable than > the derivative is defined everywhere: pw2 = Piecewise[{{x^2, x <= 0}, {x^3, x > 0}}]; pw2d = D[pw2, x] > Piecewise[{{2*x, x < 0}, {0, x == 0}}, 3*x^2] This is also as it should be. What else would you expect? Andrzej Kozlowski example that I posted (I simplified my problem by cutting and pasting an example from the help file to keep the post short). I am actually fitting cubic splines and the functions are continuous up to the second derivative (at least to the accuracy of machine precision). A better example is: In[54]:= pw[x_] := Piecewise[{{0.+ 0.007508378277320685 x + 7.561460342471517*10^-7 x^3, x < 50}, {-4.8729206849430454*10^-6 (-125.76959597633721 + x) (1148.1044516606876- 47.50636365246156 x + x^2), 50 <= x}}] In[55]:= pw[x] Out[55]= [Piecewise] { {0.+ 0.00750838 x + 7.56146*10^-7 x^3, x < 50}, {-4.87292*10^-6 (-125.77 + x) (1148.1- 47.5064 x + x^2), 50 <= x} } In[56]:= pw[50] Out[56]= 0.469937 In[57]:= pw[50 + 10^-30] Out[57]= 0.469937 In[58]:= pw[50 - 10^-30] Out[58]= 0.469937 In[60]:= pw'[x] Out[60]= [Piecewise] { {0.00750838+ 2.26844*10^-6 x^2, x < 50}, {-4.87292*10^-6 (-125.77 + x) (-47.5064 + 2 x) - 4.87292*10^-6 (1148.1- 47.5064 x + x^2), x > 50}, {Indeterminate, !(* TagBox[True, PiecewiseDefault, AutoDelete->False, DeletionWarning->True])} } In[61]:= pw'[50] Out[61]= Indeterminate In[62]:= pw'[50 + 10^-30] Out[62]= 0.0131795 In[63]:= pw'[50 - 10^-30] Out[63]= 0.0131795 Also if you Plot pw or pw' you get an annoying gap in the plot at the join (but strangely not pw''). My guess is that Mathematica is too pedantic about machine precision and is treating each piece as an algebraic equation. However this does not explain why Plot behaves funnily and doesn't help if you are trying to do numerical analysis. === Subject: Re: Problems with differentiating Piecewise functions If I set up a piecewise function and differentiate it: In[112]:= pw1 = Piecewise[{{x^2, x <= 0}, {x, x > 0}}] Out[112]= [Piecewise] { > {x^2, x <= 0}, > {x, x > 0} > } In[113]:= pw1 /. x -> 0 Out[113]= 0 In[114]:= pw1d = D[pw1, x] Out[114]= [Piecewise] { > {2 x, x < 0}, > {1, x > 0}, > {Indeterminate, !(* > TagBox[True, > PiecewiseDefault, > AutoDelete->False, > DeletionWarning->True])} > } In[115]:= pw1d /. x -> 0 Out[115]= Indeterminate Then at the joins between the pieces I get Indeterminate values, > because the limit x <= 0 has become x < 0 after differentiation. Does > anyone know a solution to this problem? > Howard. What do you mean by a solution to this problem? You have a > function that is not differentiable at 0 and you would like it's > derivative to have a value there? You can't expect a solution to a > problem when you do not tell us what is the problem (except the fact > that not all functions are differentiable - but that's life). > Note that is your pieceise function is actually differentiable than > the derivative is defined everywhere: pw2 = Piecewise[{{x^2, x <= 0}, {x^3, x > 0}}]; pw2d = D[pw2, x] > Piecewise[{{2*x, x < 0}, {0, x == 0}}, 3*x^2] This is also as it should be. What else would you expect? Andrzej Kozlowski example that I posted (I simplified my problem by cutting and pasting > an example from the help file to keep the post short). I am actually > fitting cubic splines and the functions are continuous up to the > second derivative (at least to the accuracy of machine precision). A > better example is: In[54]:= pw[x_] := > Piecewise[{{0.+ 0.007508378277320685 x + 7.561460342471517*10^-7 x^3, > x < 50}, {-4.8729206849430454*10^-6 (-125.76959597633721 + > x) (1148.1044516606876- 47.50636365246156 x + x^2), 50 <= x}}] In[55]:= pw[x] Out[55]= [Piecewise] { > {0.+ 0.00750838 x + 7.56146*10^-7 x^3, x < 50}, > {-4.87292*10^-6 (-125.77 + x) (1148.1- 47.5064 x + x^2), 50 <= x} > } In[56]:= pw[50] Out[56]= 0.469937 In[57]:= pw[50 + 10^-30] Out[57]= 0.469937 In[58]:= pw[50 - 10^-30] Out[58]= 0.469937 In[60]:= pw'[x] Out[60]= [Piecewise] { > {0.00750838+ 2.26844*10^-6 x^2, x < 50}, > {-4.87292*10^-6 (-125.77 + x) (-47.5064 + 2 x) - > 4.87292*10^-6 (1148.1- 47.5064 x + x^2), x > 50}, > {Indeterminate, !(* > TagBox[True, > PiecewiseDefault, > AutoDelete->False, > DeletionWarning->True])} > } In[61]:= pw'[50] Out[61]= Indeterminate That result is correct. > In[62]:= pw'[50 + 10^-30] Out[62]= 0.0131795 In[63]:= pw'[50 - 10^-30] Out[63]= 0.0131795 Others may have better ideas. My suggestion gives approx 0.0131795 for the derivative at 50; choose one of the three limits below. Of course, by using those limits, you are defining types of derivatives yourself: In[34]:= Limit[(pw[x + h] - pw[x])/h, h -> 0] Out[34]= Piecewise[{{2.535885030738735*^-20*(2.960851216166295*^17 + 8.9453507365065*^13*x^2), x < 50.}}, -2.1278945401599612*^-27*(1.6311721028240681*^25 - 7.93610765893554*^23*x + 6.870059478478754*^21*x^2)] In[35]:= % /. x -> 50 Out[35]= 0.0131795 In[36]:= Limit[(pw[x + h] - pw[x])/h, h -> 0, Direction -> 1] Out[36]= Piecewise[{{2.535885030738735*^-20*(2.960851216166295*^17 + 8.9453507365065*^13*x^2), x < 50.}, {-2.1278945401599612*^-27*(1.6311721028240681*^25 - 7.93610765893554*^23*x + 6.870059478478754*^21*x^2), x > 50.}}, 0.013179473534174325] In[37]:= Limit[(pw[x + h] - pw[x - h])/(2 h), h -> 0] Out[37]= Piecewise[{{2.535885030738735*^-20*(2.960851216166295*^17 + 8.9453507365065*^13*x^2), x < 50.}, {-4.2557890803199225*^-27*(8.155860514120341*^24 - 3.96805382946777*^23*x + 3.435029739239377*^21*x^2), x > 50.}}, 0.01317947353417433] > Also if you Plot pw or pw' you get an annoying gap in the plot at the > join (but strangely not pw''). For example, one can see a gap with Plot[pw[x], {x, 0, 100}]. But try Plot[pw[x], {x, 0, 50, 100}] instead; there should be no gap then. BTW, it is perhaps not strange that there was no gap when you plotted pw''. The reason there was no visible gap has to do, I suspect, with the way that Mathematica chooses points to be plotted. David > My guess is that Mathematica is too > pedantic about machine precision and is treating each piece as an > algebraic equation. However this does not explain why Plot behaves > funnily and doesn't help if you are trying to do numerical analysis. === Subject: Re: Problems with differentiating Piecewise functions >If I set up a piecewise function and differentiate it: >In[112]:= pw1 = Piecewise[{{x^2, x <= 0}, {x, x > 0}}] >Out[112]= [Piecewise] { >{x^2, x <= 0}, >{x, x > 0} >} >In[113]:= pw1 /. x -> 0 >Out[113]= 0 >In[114]:= pw1d = D[pw1, x] >Out[114]= [Piecewise] { >{2 x, x < 0}, >{1, x > 0}, >{Indeterminate, !(* >TagBox[True, >PiecewiseDefault, >AutoDelete->False, >DeletionWarning->True])} >} In[115]:= pw1d /. x -> 0 >Out[115]= Indeterminate >Then at the joins between the pieces I get Indeterminate values, >because the limit x <= 0 has become x < 0 after differentiation. Does >anyone know a solution to this problem? You haven't made it clear what you are trying to do. Clearly, the first derivative of your function is undefined at x = 0 as Mathematica is indicating. Since this is mathematically correct, there is little that can be done short of defining a different function if you want a continuous first derivative. === Subject: Collect coefficients of array variables during calculation: Hello Mathematica Friends If we have an array variable, and assuming after intermediate calculations, some equations are found to be below. eqn1=10. A[[1,1]]+b A[[1,1]]+c A[[1,2]]+3. A[[1,2]] (only for illustration) Simplify[] does not combine the coefficients under same array member, i.e. instead of (10.+b)A[[1,1]]+(c+3.)A[[1,2]], it is showing the earlier mentioned form. Is there a way to collect them and simplify them. But when I checked for simple cases, Simplify[] seems to work. Gopinath University of Oklahoma === Subject: Re: Collect coefficients of array variables during calculation: > Hello Mathematica Friends If we have an array variable, and assuming after intermediate calculations, some equations are found to be below. eqn1=10. A[[1,1]]+b A[[1,1]]+c A[[1,2]]+3. A[[1,2]] (only for illustration) Simplify[] does not combine the coefficients under same array member, i.e. instead of (10.+b)A[[1,1]]+(c+3.)A[[1,2]], it is showing the earlier mentioned form. Is there a way to collect them and simplify them. But when I checked for simple cases, Simplify[] seems to work. Actually Simplify[] does collect the terms without additional effort: In[1]:= eqn1 = 10. A[[1, 1]] + b A[[1, 1]] + c A[[1, 2]] + 3. A[[1, 2]] During evaluation of In[1]:= Part::partd: Part specification A[[1,1]] is longer than depth of object. >> During evaluation of In[1]:= Part::partd: Part specification A[[1,1]] is longer than depth of object. >> During evaluation of In[1]:= Part::partd: Part specification A[[1,2]] is longer than depth of object. >> During evaluation of In[1]:= General::stop: Further output of Part::partd will be suppressed during this calculation. >> Out[1]= 10. A[[1, 1]] + b A[[1, 1]] + 3. A[[1, 2]] + c A[[1, 2]] In[2]:= Simplify[eqn1] Out[2]= (10.+ b) A[[1, 1]] + (3.+ c) A[[1, 2]] This still doesn't change the fact that this usage of Part ([[ ... ]]) is /incorrect/, though. === Subject: Re: Collect coefficients of array variables during calculation: > Hello Mathematica Friends If we have an array variable, and assuming after intermediate > calculations, some equations are found to be below. eqn1=10. A[[1,1]]+b A[[1,1]]+c A[[1,2]]+3. A[[1,2]] (only for > illustration) Simplify[] does not combine the coefficients under same array > member, i.e. instead of (10.+b)A[[1,1]]+(c+3.)A[[1,2]], it is > showing the earlier mentioned form. Is there a way to collect them and simplify them. But when I > checked for simple cases, Simplify[] seems to work. Try this: Simplify[10. A[[1, 1]] + b A[[1, 1]] + c A[[1, 2]] + 3. A[[1, 2]] /. A[[i__]] -> A[i]] /. A[i__] -> A[[i]] Sseziwa Mukasa === Subject: Re: Collect coefficients of array variables during calculation: > Hello Mathematica Friends If we have an array variable, and assuming after intermediate calculations, some equations are found to be below. eqn1=10. A[[1,1]]+b A[[1,1]]+c A[[1,2]]+3. A[[1,2]] (only for illustration) Simplify[] does not combine the coefficients under same array member, i.e. instead of (10.+b)A[[1,1]]+(c+3.)A[[1,2]], it is showing the earlier mentioned form. Is there a way to collect them and simplify them. But when I checked for simple cases, Simplify[] seems to work. > Gopinath > University of Oklahoma > Hi Gopinath, use Collect[] to collect ;-) In[2]:= Collect[eqn1,_Part] Out[2]= (10. + b)*A[[1,1]] + (3. + c)* A[[1,2]] you can give a function as third parameter which is applied to the coefficients: In[3]:= Collect[eqn1, _Part, Rationalize] Out[3]= (10 + b)*A[[1,1]] + (3 + c)*A[[1,2]] hth, Peter === Subject: Re: Collect coefficients of array variables during calculation: > Hello Mathematica Friends If we have an array variable, and assuming after intermediate calculations, some equations are found to be below. eqn1=10. A[[1,1]]+b A[[1,1]]+c A[[1,2]]+3. A[[1,2]] (only for illustration) Simplify[] does not combine the coefficients under same array member, i.e. instead of (10.+b)A[[1,1]]+(c+3.)A[[1,2]], it is showing the earlier mentioned form. Is there a way to collect them and simplify them. But when I checked for simple cases, Simplify[] seems to work. > A[[1,1]] evaluates to something if A is a compound expression. If A is not a compound expression, then it is not correct to write A[[1,1]], and Mathematica will print an error message. So A[[1,1]] can never appear in the result of a successful calculation. === Subject: Re: Limit[(x - Log[Cosh[x]]) SinIntegral[x], x -> Infinity] > Actually a ClearSystemCache[] is enough, but since > cached results can affect the success of calculations, > probably it would be better if Mathematica did not > cache the result that it *cannot* calculate something. But then Mathematica would have to redo the calculation, and it can take a while sometimes for Mathematica to realize that it can't do a calculation, so this would cause slowdowns. Bhuvanesh, Wolfram Research === Subject: submission of a new problem; NDSolve artifacts; version 6.0.1 I have been using NDSolve as used in Restricted Three-Body Problem in 3D from The Wolfram Demonstrations Project http://demonstrations.wolfram.com/RestrictedThreeBodyProblemIn3D/ Using Version 6.0.1, I have modified the demonstration to show the classical planar, equal large masses (mu=1/2) cases as in Gass Mathematica for Scientists and Engineers: Using Mathematica to do Science Also see http://scienceworld.wolfram.com/physics/RestrictedThree-BodyProblem.html Depending on the values, there will be lines emanating from points where orbits cross. For example at tf (final time) of 45.3, the figure below is shown. However at tf = 46 no such artifact is seen. How can NDSolve be modified to eliminate these artifacts? === Subject: Re: submission of a new problem; NDSolve artifacts; version 6.0.1 No, you misunderstood me. Please do not send the notebook only to me. Instead, strip out *everything* from the commands that is not essential for reproducing the problem. Then send the set of commands to MathGroup too, as plain text. (I am CCing this message to MathGroup.) Do make sure that the reduced set of commands can be evaluated on its own, and does not depend on any variables/function that you did not provide. You have to show that you have tried to investigate the problem, and at least removed the non-essential details. Please do this next time. I was expecting something like this: tf = 45.3 tstart = 0; [Mu] = 1/2; vxinitial = -.029656755023561942249954448413973295; solution[orbtime_, Vx0_, Vy0_, [Mu]_] := NDSolve[ {x''[t] == 2 y'[t] + x[t] - ((1 - [Mu]) (x[t] + [Mu]))/((x[t] + [Mu])^2 + y[t]^2)^( 3/2) - ([Mu] (x[t] - 1 + [Mu]))/((x[t] - 1 + [Mu])^2 + y[t]^2)^(3/2), y''[t] == -2 x'[t] + y[t] - ((1 - [Mu]) y[t])/((x[t] + [Mu])^2 + y[t]^2)^( 3/2) - ([Mu] y[t])/((x[t] - 1 + [Mu])^2 + y[t]^2)^(3/2), x[0] == 0, y[0] == 858/1000, x'[0] == Vx0, y'[0] == Vy0}, {x[t], y[t]}, {t, 0, orbtime}, Method -> StiffnessSwitching] ParametricPlot3D[ Evaluate[{x[t], y[t], 0} /. solution[tf, vxinitial, 0, 1/2]], {t, tstart, tf}] Now the solution: If I understand correctly, the problem is the strange line that appears on the plot. This artefact is not from NDSolve, but from ParametricPlot3D, whose adaptive sampling method interacts badly with the interpolating function returned from NDSolve. It skips quite a large range in t. To see this, get the t values at which ParametricPlot3D samples the function and create a plot manually: sol = First@solution[tf, vxinitial, 0, 1/2]; pts = Reap[ ParametricPlot3D[ Evaluate[{x[t], y[t], 0} /. sol], {t, tstart, tf}, EvaluationMonitor :> Sow[t]]][[2, 1]]; Manipulate[ ListPlot[Take[Transpose[{x[t], y[t]} /. sol /. t -> Sort[pts]], n], Joined -> True], {n, 1, Length[pts]} ] As the slider is moved, the line jumps at one point (more precisely between the 444th and 445th points): With[{diff = Differences[Sort[pts]]}, Position[diff, Max[diff]]] This has been a common problem even with Plot in earlier versions of Mathematica, but I rarely see it in version 6. It can be cured by playing with some of the options of ParametricPlot3D, such as PlotPoints and MaxRecursion. For example, the following works: ParametricPlot3D[Evaluate[{x[t], y[t], 0} /. sol], {t, tstart, tf}, PlotPoints -> 30] > I have attached the actual notebook that I copied in the previous email. > There is not a single Mathematica command that causes the problem, but > the actual conditions in the NDSolve operations. The final time tf will show the artifact for certain values ( such as > 45.3) but not for other values (such as 46.0). > I have added to this notebook the plots of x and y which indicate some > sharp reversals of direction -- is this a potential answer? > I welcome any suggestions. > Robert M Lurie >> I have been using NDSolve as used in >> Restricted Three-Body Problem in 3D from The Wolfram >> Demonstrations Project >> http://demonstrations.wolfram.com/RestrictedThreeBodyProblemIn3D/ >> Using Version 6.0.1, I have modified the demonstration to show the >> classical planar, equal large masses (mu=1/2) cases as in Gass >> Mathematica for Scientists and Engineers: Using Mathematica to do >> Science >> Also see >> http://scienceworld.wolfram.com/physics/RestrictedThree-BodyProblem.html >> Depending on the values, there will be lines emanating from points >> where orbits cross. For example at tf (final time) of 45.3, the >> figure below is shown. However at tf = 46 no such artifact is seen. >> How can NDSolve be modified to eliminate these artifacts? > > It is not possible to give an answer unless you tell us *exactly* how > to reproduce the problem. Just post a single Mathematica command that > reproduces the problem. > > === Subject: Re: submission of a new problem; NDSolve artifacts; version 6.0.1 > I have been using NDSolve as used in > Restricted Three-Body Problem in 3D from The Wolfram Demonstrations > Project > http://demonstrations.wolfram.com/RestrictedThreeBodyProblemIn3D/ > Using Version 6.0.1, I have modified the demonstration to show the > classical planar, equal large masses (mu=1/2) cases as in Gass > Mathematica for Scientists and Engineers: Using Mathematica to do Science > Also see > http://scienceworld.wolfram.com/physics/RestrictedThree-BodyProblem.html > Depending on the values, there will be lines emanating from points where > orbits cross. For example at tf (final time) of 45.3, the figure below > is shown. However at tf = 46 no such artifact is seen. > How can NDSolve be modified to eliminate these artifacts? > It is not possible to give an answer unless you tell us *exactly* how to reproduce the problem. Just post a single Mathematica command that reproduces the problem. === Subject: Problem with FourierParameters I get a wrong result using FourierParameters: FourierTransform[f, x, w] InverseFourierTransform[%, w, x] gives 1/2 Sqrt[[Pi]/2] (Sign[1 - w] + Sign[1 + w]) Sin[x]/x which is what I expected. But with the setting of FourierParameters: FourierTransform[f, x, w, FourierParameters -> {1, -1}] InverseFourierTransform[%, w, x, FourierParameters -> {1, -1}] gives 1/2 [Pi] Sign[1 - w] + 1/2 [Pi] Sign[1 + w] <--- This is OK 0 <--- Bug? Other functions e.g. f=1/(1+x^2) transform correctly in both cases. Gruss Peter -- ==-==-==-==-==-==-==-==-==-==-==-==-==-==-==-==-==-==-==-==-==-== Peter Breitfeld, Bad Saulgau, Germany -- http://www.pBreitfeld.de === Subject: how avoid clipping labels with Combinatorica`ShowGraph? How do I avoid non-default sized vertex or edge labels from being clipped in a display created with Combinatorica's ShowGraph? For example: g=Cycle[6]; ShowGraph[g, VertexLabel -> Characters[b,a,f,e,d,c], BaseStyle -> {FontSize -> 18}] ShowGraph[g, VertexLabel -> (Style[#, FontSize -> 18] &) /@ Characters[b,a,f,e,d,c]] In both cases, the enlarged vertex labels are clipped. How can I avoid that? -- Murray Eisenberg murray@math.umass.edu Mathematics & Statistics Dept. Lederle Graduate Research Tower phone 413 549-1020 (H) University of Massachusetts 413 545-2859 (W) 710 North Pleasant Street fax 413 545-1801 Amherst, MA 01003-9305 === Subject: Re: Convert Array to Simple List Pierre, In[8]:= Flatten[{{a, b}, {c, d}}] Out[8]= {a, b, c, d} In[10]:= Flatten[Transpose[{{a, b}, {c, d}}]] Out[10]= {a, c, b, d} HTH, Syd Syd Geraghty B.Sc, M.Sc. sydgeraghty@mac.com My System Mathematica 6.0.1 for Mac OS X x86 (64 - bit) (June 19, 2007) MacOS X V 10.5 .20 > I need to convert an Array (List of List) to a simple List by > concatening the colums or the lines. e.g. : {{a,b},{c,d}} ==>{a,b,c,d} > or > {{a,b},{c,d}} ==>{a,c,b,d} > === Subject: Re: Convert Array to Simple List If the elements a,b,c,d are themselves _not_ lists, then: Flatten[{{a, b}, {c, d}}] {a, b, c, d} Flatten[Transpose[{{a, b}, {c, d}}]] {a, c, b, d} If, however, the elements may themselves be lists (and possibly nested lists), then you may want to use an additional argument to Flatten, e.g.: Flatten[{{a, {b1, b2}}, {c, d}}, 1] {a, {b1, b2}, c, d} Unless what you want in this case is also just one level of list; then: Flatten[{{a, {b1, b2}}, {c, d}}] {a, b1, b2, c, d} > I need to convert an Array (List of List) to a simple List by concatening the colums or the lines. e.g. : {{a,b},{c,d}} ==>{a,b,c,d} > or > {{a,b},{c,d}} ==>{a,c,b,d} > -- Murray Eisenberg murray@math.umass.edu Mathematics & Statistics Dept. Lederle Graduate Research Tower phone 413 549-1020 (H) University of Massachusetts 413 545-2859 (W) 710 North Pleasant Street fax 413 545-1801 Amherst, MA 01003-9305 === Subject: Re: Convert Array to Simple List > I need to convert an Array (List of List) to a simple List by > concatening the colums or the lines. e.g. : {{a,b},{c,d}} ==>{a,b,c,d} > or > {{a,b},{c,d}} ==>{a,c,b,d} > Flatten[{{a,b},{c,d}}] Sseziwa === Subject: Convert Array to Simple List I need to convert an Array (List of List) to a simple List by concatening the colums or the lines. e.g. : {{a,b},{c,d}} ==>{a,b,c,d} or {{a,b},{c,d}} ==>{a,c,b,d} === Subject: Re: Convert Array to Simple List Try these: Flatten[{{a, b, c}, {d, e, f}, {g, h, i}}] and Flatten[Transpose[{{a, b, c}, {d, e, f}, {g, h, i}}]] On Mar 27, 9:14 am, Pierre {a,b,c,d} > or > {{a,b},{c,d}} ==>{a,c,b,d} === Subject: Re: Convert Array to Simple List > I need to convert an Array (List of List) to a simple List by concatening the colums or the lines. 'Array' is not a 'List' of 'List's but a function that generates arbitrary-dimensional lists. e.g. : {{a,b},{c,d}} ==>{a,b,c,d} Join @@ {{a,b},{c,d}} or Flatten[{{a,b},{c,d}}] > or > {{a,b},{c,d}} ==>{a,c,b,d} Use Transpose first. === Subject: Re: Convert Array to Simple List what may Flatten[] do ? > I need to convert an Array (List of List) to a simple List by concatening the colums or the lines. e.g. : {{a,b},{c,d}} ==>{a,b,c,d} > or > {{a,b},{c,d}} ==>{a,c,b,d} > === Subject: Re: Convert Array to Simple List > I need to convert an Array (List of List) to a simple List by concatening the colums or the lines. e.g. : {{a,b},{c,d}} ==>{a,b,c,d} > or > {{a,b},{c,d}} ==>{a,c,b,d} In[1]:= m = {{a, b}, {c, d}}; In[2]:= Flatten@m Out[2]= {a, b, c, d} In[3]:= Flatten@Transpose@m Out[3]= {a, c, b, d} -- === Subject: Re: symbolic evaluation >I'm using Mathematica 5.1 I want to evaluate a simple equation >symbolically, such as 7x = 14. of course the answer should be x = >14/7. I can't find a clear example on how to do this with a simple >equation. Can anyone help me? Use the help browser and look at the documentation for Solve. This particular example would be done as: Solve[7 x == 14, x] === Subject: Re: Convert Array to Simple List >I need to convert an Array (List of List) to a simple List by >concatening the colums or the lines. >e.g. : {{a,b},{c,d}} ==>{a,b,c,d} or {{a,b},{c,d}} ==>{a,c,b,d} Look up Flatten in the documentation, i.e., In[1]:= Flatten[{{a, b}, {c, d}}] Out[1]= {a,b,c,d} === Subject: Re: Limit[(x - Log[Cosh ]) SinIntegral , x -> Infinity] > I confirm the precise behavior you described. It's surprising that a >> restart was required. > Actually a ClearSystemCache[] is enough, but since cached results can > affect the success of calculations, probably it would be better if > Mathematica did not cache the result that it *cannot* calculate > something. > [...] I beg to differ. If that nonevaluation result is time consuming to compute, and is something that might show up in a context where recomputation is an issue, then caching can save considerable time. Limits tend to be recomputed when one does, say, a definite integral requiring several different tactics. Caching them thus can reduce timings of Integrate, a notoriously slow function. Daniel Lichtblau Wolfram Research === Subject: Re: Limit[(x - Log[Cosh ]) SinIntegral , x -> Infinity] > [...] > But I am still curious about why Mathematica can compute the two > limits separately but not the limit of their product. Offhand I do not know. I found that both give results in the development version, hence had insufficient incentive to look further. > I could imagine > that Limit[] has some built-in constraints, e.g. it only tries a > limited number of transformations on the expression, or it has some > internal time constraints. If I understood correctly, Bob Hanlon > reported that Mathematica does give an answer on his computer---this > could be explained by time constraints and a faster computer. Yes, this could be what is behind it. Also there are some leaf count constraints used in places. Neither is as big an issue as are constraints used in definite integration, but they are indeed present, to an extent, in Limit. > If this is really the case, is there a way to ask Mathematica to work > harder (perhaps try longer), so that it will be able to give an > answer? (For example, Simplify has the option TimeConstraint.) Szabolcs HorvÌÁt At this time there is no such option. Not even a hidden one. (Or, if there is such, it is hidden from me.) Daniel Lichtblau Wolfram Research === Subject: Re: Limit[(x - Log[Cosh ]) SinIntegral , x -> Infinity] > > Actually a ClearSystemCache[] is enough, but since cached results can > affect the success of calculations, probably it would be better if > Mathematica did not cache the result that it *cannot* calculate > something. > [...] I beg to differ. If that nonevaluation result is time consuming to > compute, and is something that might show up in a context where > recomputation is an issue, then caching can save considerable time. Limits tend to be recomputed when one does, say, a definite integral > requiring several different tactics. Caching them thus can reduce > timings of Integrate, a notoriously slow function. That is a very good point. But I am still curious about why Mathematica can compute the two limits separately but not the limit of their product. I could imagine that Limit[] has some built-in constraints, e.g. it only tries a limited number of transformations on the expression, or it has some internal time constraints. If I understood correctly, Bob Hanlon reported that Mathematica does give an answer on his computer---this could be explained by time constraints and a faster computer. If this is really the case, is there a way to ask Mathematica to work harder (perhaps try longer), so that it will be able to give an answer? (For example, Simplify has the option TimeConstraint.) Szabolcs HorvÌÁt === Subject: Re: The FinancialData Function I called Wolfram and asked the same question. I gather the FinancialData[] information is taken from data packlets on a Yahoo server, and other sources. This funtion has the potential to be VERY usefull to small enterprises and individuals like me who don't have access to realtime equities data. Now, I've tried to use FD to monitor the performance of my stock portfolio and ran into problems with some of the international (Canada, Australia etc.) stocks. While this was frustrating I was able to get information on all my US and most of my internationals. I presume you have looked at the Help Documentation and at the Wolfram Site - it gives enough to make a good start, but there seems to be a mismatch between the functionality of FinancialData[] and information available at the servers. This means you can make calls and get nothing back. In that regard the documentation could be improved. Now one caveat. I am not so sure - having spoken to WRI - that they realise there should be some obligation on their part to maintain FinancialData as a core function in Mathematica. Their tech suppport gave me the impression that FD is being trialed and that its continuance was to some degree dependent on their having free (or cheap) access to the data servers. This scared me a little since I have already spent significant amounts of time writing my portfolio tracker and I can imagine there are small enterprises out there who are doing the same. It seems like WRI could leave us stranded if they don't continue to provide this function in Mathematica. BTW - the inclusion of Curated Knowledge like FD into Mathematica 6. is pretty stunning. I am sure McKinsey and Co would have charged me a few hundred thousand dollars to write my portfolio tracker - instead I spend a few evening a week for a month and bingo I am getting the same information tha Charles Schab gives me plus the ability to analyze - well done WRI ! I would be intereseted to hear from others. Can anyone tell me where I can get more information about the data sources for Mathematica's new function FinancialData? Gregory Robert Prince-Wright Houston TX, 77006 USA === Subject: IsIntegerOrFloat fine now. Here is another question - I apologize if it has been asked before. I need a function IsIntegerOrFloat[expr] that returns True if expr, which is generally a flat list, contains only integers or floating point numbers, and False otherwise. Rational numbers such as 1/2 are considered symbolic for this test; so is [Pi] or Sqrt[5]. Appearance of any symbol, as in 2.0*a+3.5, makes it False. As in previous questions, this should work on versions >=4.0. Use: unified printing of simulation data structures in table formats. Expressions containing only integers or floats are filtered through PaddedForm[] and ToString[], others through Symbol[]. The end result (a flat table of strings) is filtered through TableForm with appropriate options. === Subject: Re: IsIntegerOrFloat One possibility is: IsIntegerOrFloat[expr_] := VectorQ[expr, NumberQ[#] && (Head[#] =!= Rational) && (Head[#] =!= Complex) &] Then IsIntegerOrFloat[{2.3, 5}] True IsIntegerOrFloat[{2.3, 1/2}] False and so on. Andrzej Kozlowski > work > fine now. Here is another question - I apologize if it has been > asked before. > I need a function IsIntegerOrFloat[expr] that returns True if expr, which is generally a flat list, contains > only integers or floating point numbers, and False otherwise. > Rational numbers such as 1/2 are considered symbolic for this test; > so is > [Pi] or Sqrt[5]. Appearance of any symbol, as in 2.0*a+3.5, makes > it False. > As in previous questions, this should work on versions >=4.0. Use: unified printing of simulation data structures in table formats. > Expressions containing only integers or floats are filtered through > PaddedForm[] and ToString[], others through Symbol[]. The end > result (a flat table of strings) is filtered through TableForm with > appropriate options. > === Subject: Re: IsIntegerOrFloat > I need a function IsIntegerOrFloat[expr] that returns True if expr, which is generally a flat list, contains > only integers or floating point numbers, and False otherwise. > Rational numbers such as 1/2 are considered symbolic for this test; so is > [Pi] or Sqrt[5]. Appearance of any symbol, as in 2.0*a+3.5, makes it False. > As in previous questions, this should work on versions >=4.0. The following should do what you are looking for (compatible with 4.0+) at a reasonable speed (~200,000 entries processed in about 0.5 second) IsIntegerOrFloat[expr_] := Cases[expr, 1] /. {False} -> False /. {} -> True Some tests and benchmarking follows. In[1]:= IsIntegerOrFloat[expr_] := Cases[expr, 1] /. {False} -> False /. {} -> True In[2]:= data = {1, 1., Pi, 1/2, 2.0*a + 3.5}; Head /@ data IsIntegerOrFloat@data Out[3]= {Integer, Real, Symbol, Rational, Plus} Out[4]= False In[5]:= data = {1, 1., N@Pi, N@1/2, 2.0*a + 3.5 /. a -> 1}; Head /@ data IsIntegerOrFloat@data Out[6]= {Integer, Real, Real, Real, Real} Out[7]= True In[8]:= tst = Join[{a}, RandomInteger[{-1000, 1000}, {10^5}], RandomReal[{0, 1}, {10^5}]]; IsIntegerOrFloat@tst // Timing tst = Join[RandomInteger[{-1000, 1000}, {10^5}], {a}, RandomReal[{0, 1}, {10^5}]]; IsIntegerOrFloat@tst // Timing tst = Join[RandomInteger[{-1000, 1000}, {10^5}], RandomReal[{0, 1}, {10^5}], {a}]; IsIntegerOrFloat@tst // Timing tst = Join[RandomInteger[{-1000, 1000}, {10^5}], RandomReal[{0, 1}, {10^5}]]; IsIntegerOrFloat@tst // Timing Out[9]= {0.003186, False} Out[11]= {0.227702, False} Out[13]= {0.50994, False} Out[15]= {0.50495, True} -- === Subject: Re: IsIntegerOrFloat > fine now. Here is another question - I apologize if it has been asked before. > I need a function IsIntegerOrFloat[expr] that returns True if expr, which is generally a flat list, contains > only integers or floating point numbers, and False otherwise. > Rational numbers such as 1/2 are considered symbolic for this test; so is > [Pi] or Sqrt[5]. Appearance of any symbol, as in 2.0*a+3.5, makes it False. > As in previous questions, this should work on versions >=4.0. Use: unified printing of simulation data structures in table formats. > Expressions containing only integers or floats are filtered through > PaddedForm[] and ToString[], others through Symbol[]. The end > result (a flat table of strings) is filtered through TableForm with > appropriate options. Conversion to strings is generally not necessary for simple formatting ... === Subject: Re: IsIntegerOrFloat > I need a function IsIntegerOrFloat[expr] that returns True if expr, which is generally a flat list, contains > only integers or floating point numbers, and False otherwise. > Rational numbers such as 1/2 are considered symbolic for this test; so is > [Pi] or Sqrt[5]. Appearance of any symbol, as in 2.0*a+3.5, makes it False. > As in previous questions, this should work on versions >=4.0. > Is this what you need? In[45]:= ClearAll[IsIntegerOrFloat] In[47]:= IsIntegerOrFloat[n_Real]:=True In[48]:= IsIntegerOrFloat[n_Integer]:=True In[54]:= IsIntegerOrFloat[lst_List]:=And@@(IsIntegerOrFloat/@lst) In[55]:= IsIntegerOrFloat[___]:=False In[56]:= IsIntegerOrFloat[1] Out[56]= True In[57]:= IsIntegerOrFloat[1/3] Out[57]= False In[58]:= IsIntegerOrFloat[1.4] Out[58]= True In[59]:= IsIntegerOrFloat[[Pi]] Out[59]= False In[60]:= IsIntegerOrFloat[2.0*a+3.5] Out[60]= False In[61]:= IsIntegerOrFloat[{1,2,3,0.8,6.9}] Out[61]= True In[62]:= IsIntegerOrFloat[{1,2,3,0.8,6.9,1/2}] Out[62]= False In[63]:= IsIntegerOrFloat[{1,2,3,0.8,6.9,a}] Out[63]= False I think this would even work with version 1 or 2 :-) hth, albert === Subject: Re: IsIntegerOrFloat This list should test as True: nodxyz={{1}, {5}, {2, 0.33333, 4.}, {156.9925, 2.23606}}; > Print[IIOF[nodxyz]=,IIOF[nodxyz]]; False Well, you explicitly said flat list in the original request, didn't you? If it's not flat, flatten it before passing it to the function. (See the docs for Flatten) === Subject: Re: IsIntegerOrFloat > fine now. Here is another question - I apologize if it has been asked before. > I need a function IsIntegerOrFloat[expr] that returns True if expr, which is generally a flat list, contains > only integers or floating point numbers, and False otherwise. > Rational numbers such as 1/2 are considered symbolic for this test; so is > [Pi] or Sqrt[5]. Appearance of any symbol, as in 2.0*a+3.5, makes it False. > As in previous questions, this should work on versions >=4.0. Use: unified printing of simulation data structures in table formats. > Expressions containing only integers or floats are filtered through > PaddedForm[] and ToString[], others through Symbol[]. The end > result (a flat table of strings) is filtered through TableForm with > appropriate options. > Hi Carlos this seems to work: IsIntegerOrFloat[list_] := With[{ll = Flatten@list}, If[Length[ll] == Length[Cases[ll, _Real | _Integer]], True, False]] l1={1, 2.0, [Pi], a, b, Sqrt[2]} l2 = Union[RandomInteger[{1, 10}, {5}], RandomReal[{1, 10}, {5}]] l3 = {1, {2.1, {1.6, 2, 5}}, 6} l4 = {1, {2.1, {1.6, Pi, 5}}, 6} IsIntegerOrFloat[l1] ---> False IsIntegerOrFloat[l2] ---> True IsIntegerOrFloat[l3] ---> True IsIntegerOrFloat[l4] ---> False Gruss Peter -- ==-==-==-==-==-==-==-==-==-==-==-==-==-==-==-==-==-==-==-==-==-== Peter Breitfeld, Bad Saulgau, Germany -- http://www.pBreitfeld.de === Subject: Re: Collect coefficients of array variables during Off[Part::partd, Part::pspec]; eqn1 = 10. A[[1, 1]] + b A[[1, 1]] + c A[[1, 2]] + 3. A[[1, 2]]; eqn1 // Simplify (b+10.) A[[1,1]]+(c+3.) A[[1,2]] If Simplify doesn't work try FullSimplify or hit it with a hammer: Collect[eqn1, Union[Cases[eqn1, A[[__]], Infinity]]] (b+10.) A[[1,1]]+(c+3.) A[[1,2]] Bob Hanlon > Hello Mathematica Friends If we have an array variable, and assuming after intermediate calculations, some equations are found to be below. eqn1=10. A[[1,1]]+b A[[1,1]]+c A[[1,2]]+3. A[[1,2]] (only for illustration) Simplify[] does not combine the coefficients under same array member, i.e. instead of (10.+b)A[[1,1]]+(c+3.)A[[1,2]], it is showing the earlier mentioned form. Is there a way to collect them and simplify them. But when I checked for simple cases, Simplify[] seems to work. > Gopinath > University of Oklahoma > === Subject: Re: Find Upper Neighbor in a list Hi Oleksandr, I downloaded and looked with interest at your notebook in http://tinyurl.com/3a7k65 I'd like to ask you - do you have developed code for checking if a poset is a lattice? alessandro I forgot to mention: > {1,5,6}, {1,2,5,6}, {1,3,5,6} (all combinations of different sets containing {5,6}) are upper neighbors of {5,6] when they appear in the basis list. And through their length they can be traced easily (see the module). Because some lengths just do not appear this way of doing it could result in a more efficient solution.But again: for now it is difficult for me to formulate that in Mathematica. I need some examples. > P_ter > If we add these instances, el = {{5, 6}, {1, 5, 6}, {5, 6, 8}, {1, 2, 5, 6}, {1, 3, 5, > 6}, {5, 6, 7, 8}, {1, 2, 3, 5, 6}, {1, 2, 3, 4, 5, 6, 7, 8}}; the upper neighbours are now {5,6,8} and {1, 5, 6}, as far as I can > say, because {5,6} [Element] {1,5,6} [Element] {1,2,5,6} and similarly for > {1,3,5,6}. Now, packaging the code I posted earlier: Poset[el_List?OrderedPosetQ] := Module[{e2, graph}, > e2 = Cases[Rule @@@ Subsets[el, {2}], > graph = FixedPoint[ > Cases[#, HoldPattern[x_ -> y_] /; > Cases[el, z_ /; MemberQ[#, Rule[z, y]] && > graph > ] UpperNeighbours[el_List?OrderedPosetQ] := > ReplaceList[First[el],Poset[el]] we get: In[85]:= UpperNeighbours[el] Out[85]= {{1, 5, 6}, {5, 6, 8}} It is easy to generate such posets randomly for testing purposes. RandomPoset[ra_, {lb_, ub_}, n_] := Module[{subs, ran, ran1, el}, > subs = Subsets[Range[ra], {lb, ub}]; > While[ > Position[ ran = Sort[ > RandomSample[subs, Min[n, Length[subs]]]], {_, _}, {1}, > 1] =!= {}, > ran1 = First[ran]; > el = Cases[ran, x_ /; ran1 == Intersection[x, ran1]] > ]; el] This can now be used for performance comparisons. In[123]:= BlockRandom[RandomSeed[2008]; > Length[el = RandomPoset[15, {2, 7}, 10^3]]] Out[123]= 164 In[124]:= Timing[graph =Poset[el];] Out[124]= {7.656, Null} In[125]:= First[el] Out[125]= {8, 14} In[126]:= ReplaceList[el[[1]], graph] Out[126]= {{6, 8, 14}, {8, 11, 14}, {2, 3, 8, 14}, {2, 7, 8, 14}, {4, > 8, 9, 14}, {7, 8, 13, 14}, {8, 9, 12, 14}, {8, 10, 13, 14}, {8, 13, > 14, 15}, {1, 4, 8, 12, 14}, {1, 8, 12, 13, 14}, {2, 4, 8, 13, > 14}, {2, 8, 12, 14, 15}, {3, 5, 8, 14, 15}, {4, 5, 8, 13, 14}, {4, > 8, 10, 14, 15}, {5, 7, 8, 14, 15}, {1, 5, 8, 10, 14, 15}, {3, 4, 7, > 8, 12, 14}, {1, 3, 5, 7, 8, 12, 14}} You can try if the code works fine for your problems, or if it simply > stalls. Let me know. Additionally, you might find the package 'posets' by John Stembridge > of > interest ( seehttp://tinyurl.com/2q46fu). The notebook with the code posted, as well as additional examples can > be > found at http://tinyurl.com/3a7k65 Oleksandr === Subject: Dynamic and J/Link I'm using Java to do some agent-based modeling and am wondering what the best way is to create a dynamic graphic that will update automatically whenever the state of the simulation changes. Suppose - for sake of argument - that the simulation is a single Java object saved in a Mathematica variable called model. Suppose that calling the Java method step() advances the simulation one iteration and that calling the Java method getState() returns a rectangular 2D array of 0s and 1s. Now, one easy way of representing the state of the model is by using Raster, so the following gives a basic graphic representation: Graphics[ Raster[model@getState[]] ] Suppose, now, that we wrap that statement with Dynamic as follows: Dynamic[ Graphics[ Raster[ model@getState[] ] ] ] If I then evaluate the following, the displayed graphic doesn't change at all, even though (intuitively, at least) it should: model@step[]; Update[ model ] For some reason, calling Update on the variable model doesn't cause the Dynamic object in the notebook to recognize that it needs to refresh the displayed graphic. Why is that? Now, the only way I've found to solve this problem is the draw the display using a second variable which contains a local copy of the state of the Java object. First, set up the initial display in the notebook as follows: array = model@getState[]; Dynamic[ Graphics[ Raster[ array ] ] ] then manually update the variable array each time the simulation changes: model@step[]; array = model@getState[]; (* This triggers a redisplay *) The two irritations about this are that it (a) it requires polluting the current Mathematica's session namespace with another variable that doesn't do anything except hold a value which could be easily obtained by calling model@getState[], and (b) it requires some (minor) additional code to configure each display. Those aren't real worries, but it does suggest that I'm not doing this the most efficient way. Is the above solution the best (or, indeed, only) way to get Dynamic to recognize state changes of J/Link objects? Does anyone else have any other suggestions? Jason -- Dr. J. McKenzie Alexander Department of Philosophy, Logic and Scientific Method London School of Economics and Political Science Houghton Street, London WC2A 2AE Please access the attached hyperlink for an important electronic communications disclaimer: http://www.lse.ac.uk/collections/secretariat/legal/disclaimer.htm === Subject: Re: Dynamic and J/Link > I'm using Java to do some agent-based modeling and am wondering what > the best way is to create a dynamic graphic that will update > automatically whenever the state of the simulation changes. Suppose - for sake of argument - that the simulation is a single Java > object saved in a Mathematica variable called model. Suppose that > calling the Java method step() advances the simulation one iteration > and that calling the Java method getState() returns a rectangular 2D > array of 0s and 1s. Now, one easy way of representing the state of > the model is by using Raster, so the following gives a basic graphic > representation: Graphics[ Raster[model@getState[]] ] Suppose, now, that we wrap that statement with Dynamic as follows: Dynamic[ > Graphics[ Raster[ model@getState[] ] ] > ] If I then evaluate the following, the displayed graphic doesn't change > at all, even though (intuitively, at least) it should: model@step[]; > Update[ model ] For some reason, calling Update on the variable model doesn't cause > the Dynamic object in the notebook to recognize that it needs to > refresh the displayed graphic. Why is that? Now, the only way I've found to solve this problem is the draw the > display using a second variable which contains a local copy of the > state of the Java object. First, set up the initial display in the > notebook as follows: array = model@getState[]; > Dynamic[ > Graphics[ Raster[ array ] ] > ] then manually update the variable array each time the simulation > changes: model@step[]; > array = model@getState[]; (* This triggers a redisplay *) The two irritations about this are that it (a) it requires polluting > the current Mathematica's session namespace with another variable that > doesn't do anything except hold a value which could be easily obtained > by calling model@getState[], and (b) it requires some (minor) > additional code to configure each display. Those aren't real worries, > but it does suggest that I'm not doing this the most efficient way. Is the above solution the best (or, indeed, only) way to get Dynamic > to recognize state changes of J/Link objects? Does anyone else have > any other suggestions? > Jason -- > Dr. J. McKenzie Alexander > Department of Philosophy, Logic and Scientific Method > London School of Economics and Political Science > Houghton Street, London WC2A 2AE > Please access the attached hyperlink for an important electronic communications disclaimer: http://www.lse.ac.uk/collections/secretariat/legal/disclaimer.htm > Your variable 'model' contains a reference to an instance of a Java class (somewhat analogous to a pointer in C), it does not contain the instance itself, which lies in a completely separate Java process. Thus, as far as Mathematica is concerned, the variable does not change when you call step. I would just wrap your two lines in a function and call that: UpdateModel[]:= ( model@step[]; array=model@getState[]; ); David Bailey http://www.dbaileyconsultancy.co.uk === Subject: Re: Dynamic and J/Link > I'm using Java to do some agent-based modeling and am wondering what > the best way is to create a dynamic graphic that will update > automatically whenever the state of the simulation changes. Suppose - for sake of argument - that the simulation is a single Java > object saved in a Mathematica variable called model. Suppose that > calling the Java method step() advances the simulation one iteration > and that calling the Java method getState() returns a rectangular 2D > array of 0s and 1s. Now, one easy way of representing the state of > the model is by using Raster, so the following gives a basic graphic > representation: Graphics[ Raster[model@getState[]] ] Suppose, now, that we wrap that statement with Dynamic as follows: Dynamic[ > Graphics[ Raster[ model@getState[] ] ] > ] If I then evaluate the following, the displayed graphic doesn't change > at all, even though (intuitively, at least) it should: model@step[]; Note that I do not know Java, so I never used JLink. However, I suspect that 'model' only contains a reference to a Java object, so technically its value does not change within Mathematica. > Update[ model ] Also, Update[] does not seem to affect the display of Dynamic expressions at all. Not even in the example on Update's doc page (try Dynamic[t] there). I wonder why Update[] is listed in the see also section of so many dynamic-related functions. For some reason, calling Update on the variable model doesn't cause > the Dynamic object in the notebook to recognize that it needs to > refresh the displayed graphic. Why is that? Now, the only way I've found to solve this problem is the draw the > display using a second variable which contains a local copy of the > state of the Java object. First, set up the initial display in the > notebook as follows: array = model@getState[]; > Dynamic[ > Graphics[ Raster[ array ] ] > ] then manually update the variable array each time the simulation > changes: model@step[]; > array = model@getState[]; (* This triggers a redisplay *) The two irritations about this are that it (a) it requires polluting > the current Mathematica's session namespace with another variable that > doesn't do anything except hold a value which could be easily obtained > by calling model@getState[], and (b) it requires some (minor) > additional code to configure each display. Those aren't real worries, > but it does suggest that I'm not doing this the most efficient way. You should take a look at Refresh[], but I think that your solution is a better one. Explicitly chaging a variable's value seems to be the way to let the system know that certain Dynamic expressions must be updated. Is the above solution the best (or, indeed, only) way to get Dynamic > to recognize state changes of J/Link objects? Does anyone else have > any other suggestions? === Subject: Re: smallest fraction For matemathical problem see example http://www.research.att.com/~njas/sequences/A138343 MATHEMATICA PROBLEM 1) N[Pi,n+1] approximate to n decimal digits (not truncate) 2) We do set of lower approximations taken from reversed Continued fractions (even are lower odd are upper limits Pi) {n, 2, 100, 2}]; a 3) we do LLL set (particular because we use decimal systam) by << NumberTheory`Recognize` c = {}; b = {}; a = {}; Do[k = Recognize[N[Pi, n + 1], 1, x]; If[MemberQ[a, k], AppendTo[b, n], w = Solve[k == 0, x]; AppendTo[c, x /. w[[1]]]; AppendTo[a, k]], {n, 2, 100}]; c 4) Now we compare Complement[a,c] and Complement[c,a] and we can observe differences between these two methods 5) Not all recognize results are lower limits but all are continued fractions what we can check {n, 2, 100}]; d and now Complement[c,d]={} what mean that Recognize uses similar alhorhitms as ContinuedFractions as Daniel say. Artur Jasinski BEST WISHES ARTUR Andrzej Kozlowski pisze: > >> > I note however that: > a = RootApproximant[Pi, 1] > 80143857/25510582 > and > Rationalize[Pi, 10^(-15)] > 80143857/25510582 > which are exactly the same. As far as I know Rationalize does not > use lattice reduction (?) but a different algorithm, related to > the way one obtains a continuous fraction expansion of Pi (at > least I blieve that this is what Rationalze does). I am not sure > if the fact that the same answer is returned by the above is a > coincidence or it means that in fact the two algorithms amount to > the same thing in this particular case ? > Andrzej Kozlowski > [...] > >> They are different. The LLL (or PSLQ) based aproach is sometimes >> regarded as a higher dimensional analog to continued fraction >> approximation. I believe tehre is a way of casting it that shows a >> relation between the methods. But I am not even certain of this, let >> alone know how to show it myself. >> The operation of the LLL approach, in the degree one case, is this. >> We pick some digit size, say 16 (so as to be around >> $MachinePrecision, just for illustration purposes). We multiply our >> goal, Pi, by that number, and round off. Call this goal. We then >> form the lattice lat= >> {{1,0,goal}, >> { 0,1,10^16}} >> We reduce this to reducedlat, and look at the shortest vector, call >> it {a,b,c}. The identity matrix at the left of 'lat' has in effect >> recorded row operations needed to form this vector. In nice cases, c >> will be small, indicating that we obtain an approximate zero as >> a*goal+b*10^16. But this simply means that goal is approximately - >> b*10^16/a, hence Pi is approximately -b/a. >> In this example: >> In[101]:= InputForm[-redlat[[1,2]]/redlat[[1,1]]] >> Out[101]//InputForm= 80143857/25510582 >> It is reasonable to ask whether this approach, if used at the same >> precision/#digits as Rationalize, will always give the same result. >> I do not know. But I would expect them to be close, and usually >> identical. Reason being, both tend to find a result with small >> numerator and denominator, with small typically being around half >> the number of digits we use in our approximation. There are not >> likely to be too many contenders. >> Daniel Lichtblau >> Wolfram Research >> > I realize now (I think I noticed this already one a long time ago but > forgot) that this way of using LLL seems rather different from the one > I once learned and tried to (roughly ) describe in this thread. In > particular, the approach to recognizing algebraics you describe only > uses lattice reduction for the standard euclidean inner product (or > the standard norm) whereas the approach that I had in mind (described, > for example, in Henri Cohen's Course in Computational Number Theory, > page 100), uses lattice reduction for a specially constructed > positive definite quadratic form. The two approaches appear to be > equivalent but I can't at this time clarify the relationship between > them. Is there something obvious that I am missing? Furthermore, I have notice that Developer`SystemOptions[LatticeReduceOptions] > {LatticeReduceOptions - {LatticeReduceArithmetic -> Integers, > LatticeReduceInnerProduct -> Automatic, > LatticeReduceRatioParameter -> Automatic}} makes it possible to use a non-standard inner product in > LatticeReduction. Presumably a custom inner product should be > specified as a pure function? > I guess that should make it possible to implement the alternative > approach described in Cohen's book?. (Of course if they are clearly > equivalent there would be not much point doing this but if is not > obvious it might be interesting to compare the answers one gets from > each of them). Andrzej Kozlowski > ____ NOD32 Informacje 2701 (20071204) ____ Wiadomosc zostala sprawdzona przez System Antywirusowy NOD32 > http://www.nod32.com lub http://www.nod32.pl === Subject: Re: smallest fraction > [...] I realize now (I think I noticed this already one a long time ago but > forgot) that this way of using LLL seems rather different from the one > I once learned and tried to (roughly ) describe in this thread. In > particular, the approach to recognizing algebraics you describe only > uses lattice reduction for the standard euclidean inner product (or > the standard norm) whereas the approach that I had in mind (described, > for example, in Henri Cohen's Course in Computational Number Theory, > page 100), uses lattice reduction for a specially constructed > positive definite quadratic form. The two approaches appear to be > equivalent but I can't at this time clarify the relationship between > them. Is there something obvious that I am missing? Yes, the fact that I had multiplied the number by a large constant before rounding. That constant (10^16, in my example) was effectively the square root of the N in Cohen's exposition. That is to say, his inner product is given by the diagonal matrix with main diagonal {1,1,...,1,sqrt(N)}. > Furthermore, I have notice that Developer`SystemOptions[LatticeReduceOptions] > {LatticeReduceOptions - {LatticeReduceArithmetic -> Integers, > LatticeReduceInnerProduct -> Automatic, > LatticeReduceRatioParameter -> Automatic}} makes it possible to use a non-standard inner product in > LatticeReduction. Presumably a custom inner product should be > specified as a pure function? Yes. Example below. The reason this option is hidden as a system option and not in LatticeReduce is that the code has not been made bullet proof against bad inner products e.g. ones that do not correspond to symmetric positive definite matrices. Here is a quick example of usage. lat = {{1,0,125123},{0,1,51253}}; Reduce this using thedefault Automatic setting. In[8]:= redlat = LatticeReduce[lat] Out[8]= {{34, -83, 183}, {213, -520, -361}} Recall that lat is in Hermite normal form. Suppose we started with redlat, and wished to recover the HNF using lattice reduction. We can do this by weighting the inner product so that earlier columns count for more than later ones. This is in effect a simple diagonal inner product matrix. I implement it using apprpriate rescaling of one vector. In[17]:= SetSystemOptions[LatticeReduceOptions-> {LatticeReduceInnerProduct->(({2^100,2^50,1}*#1).#2&)}]; In[18]:= lat2 = LatticeReduce[redlat] Out[18]= {{0, 1, 51253}, {1, 0, 125123}} > I guess that should make it possible to implement the alternative > approach described in Cohen's book?. (Of course if they are clearly > equivalent there would be not much point doing this but if is not > obvious it might be interesting to compare the answers one gets from > each of them). Andrzej Kozlowski === Subject: Re: smallest fraction > I note however that: a = RootApproximant[Pi, 1] > 80143857/25510582 and Rationalize[Pi, 10^(-15)] > 80143857/25510582 which are exactly the same. As far as I know Rationalize does not use > lattice reduction (?) but a different algorithm, related to the way > one obtains a continuous fraction expansion of Pi (at least I blieve > that this is what Rationalze does). I am not sure if the fact that the > same answer is returned by the above is a coincidence or it means that > in fact the two algorithms amount to the same thing in this particular > case ? Andrzej Kozlowski > [...] They are different. The LLL (or PSLQ) based aproach is sometimes regarded as a higher dimensional analog to continued fraction approximation. I believe tehre is a way of casting it that shows a relation between the methods. But I am not even certain of this, let alone know how to show it myself. The operation of the LLL approach, in the degree one case, is this. We pick some digit size, say 16 (so as to be around $MachinePrecision, just for illustration purposes). We multiply our goal, Pi, by that number, and round off. Call this goal. We then form the lattice lat= {{1,0,goal}, { 0,1,10^16}} We reduce this to reducedlat, and look at the shortest vector, call it {a,b,c}. The identity matrix at the left of 'lat' has in effect recorded row operations needed to form this vector. In nice cases, c will be small, indicating that we obtain an approximate zero as a*goal+b*10^16. But this simply means that goal is approximately -b*10^16/a, hence Pi is approximately -b/a. In this example: In[101]:= InputForm[-redlat[[1,2]]/redlat[[1,1]]] Out[101]//InputForm= 80143857/25510582 It is reasonable to ask whether this approach, if used at the same precision/#digits as Rationalize, will always give the same result. I do not know. But I would expect them to be close, and usually identical. Reason being, both tend to find a result with small numerator and denominator, with small typically being around half the number of digits we use in our approximation. There are not likely to be too many contenders. Daniel Lichtblau Wolfram Research === Subject: Re: smallest fraction >> I note however that: >> a = RootApproximant[Pi, 1] >> 80143857/25510582 >> and >> Rationalize[Pi, 10^(-15)] >> 80143857/25510582 >> which are exactly the same. As far as I know Rationalize does not >> use lattice reduction (?) but a different algorithm, related to >> the way one obtains a continuous fraction expansion of Pi (at >> least I blieve that this is what Rationalze does). I am not sure >> if the fact that the same answer is returned by the above is a >> coincidence or it means that in fact the two algorithms amount to >> the same thing in this particular case ? >> Andrzej Kozlowski >> [...] They are different. The LLL (or PSLQ) based aproach is sometimes > regarded as a higher dimensional analog to continued fraction > approximation. I believe tehre is a way of casting it that shows a > relation between the methods. But I am not even certain of this, let > alone know how to show it myself. The operation of the LLL approach, in the degree one case, is this. > We pick some digit size, say 16 (so as to be around > $MachinePrecision, just for illustration purposes). We multiply our > goal, Pi, by that number, and round off. Call this goal. We then > form the lattice lat= {{1,0,goal}, > { 0,1,10^16}} We reduce this to reducedlat, and look at the shortest vector, call > it {a,b,c}. The identity matrix at the left of 'lat' has in effect > recorded row operations needed to form this vector. In nice cases, c > will be small, indicating that we obtain an approximate zero as > a*goal+b*10^16. But this simply means that goal is approximately - > b*10^16/a, hence Pi is approximately -b/a. In this example: In[101]:= InputForm[-redlat[[1,2]]/redlat[[1,1]]] > Out[101]//InputForm= 80143857/25510582 It is reasonable to ask whether this approach, if used at the same > precision/#digits as Rationalize, will always give the same result. > I do not know. But I would expect them to be close, and usually > identical. Reason being, both tend to find a result with small > numerator and denominator, with small typically being around half > the number of digits we use in our approximation. There are not > likely to be too many contenders. Daniel Lichtblau > Wolfram Research > I realize now (I think I noticed this already one a long time ago but forgot) that this way of using LLL seems rather different from the one I once learned and tried to (roughly ) describe in this thread. In particular, the approach to recognizing algebraics you describe only uses lattice reduction for the standard euclidean inner product (or the standard norm) whereas the approach that I had in mind (described, for example, in Henri Cohen's Course in Computational Number Theory, page 100), uses lattice reduction for a specially constructed positive definite quadratic form. The two approaches appear to be equivalent but I can't at this time clarify the relationship between them. Is there something obvious that I am missing? Furthermore, I have notice that Developer`SystemOptions[LatticeReduceOptions] {LatticeReduceOptions -> {LatticeReduceArithmetic -> Integers, LatticeReduceInnerProduct -> Automatic, LatticeReduceRatioParameter -> Automatic}} makes it possible to use a non-standard inner product in LatticeReduction. Presumably a custom inner product should be specified as a pure function? I guess that should make it possible to implement the alternative approach described in Cohen's book?. (Of course if they are clearly equivalent there would be not much point doing this but if is not obvious it might be interesting to compare the answers one gets from each of them). Andrzej Kozlowski === Subject: Re: smallest fraction One more remark about the quadratic form mentioned below: in the most usual approach to the problem of approximating numbers by algebraic numbers, the form looks like this: a0^2+a1^2+a2^2+ ... + an^2 + M*(a0+a1 z^2+ ...an z^n)^2 where M is some large number (ai are all integers) and z is the number we wish to approximate by an algebraic number. The LLL algorithm produces a short vector with respect to this form, which means that approximately a0+a1 z^2+ ...an z^n = 0 and (a1,a2,...an) is a short vector in the usual norm. So, in the case when n =1 this is similar to minimizing p^2+q^2, but of course not exactly so. Andrzej Kozlowksi > I only realized the point of the question the day after I posted the > reply below. > I see now it is only concerned with what happens here: RootApproximant[Pi, 1] > 80143857/25510582 that with the special case when we approximate a real number by an > algebraic number of degree 1, i.e. a rational. Of course > RootApproximant is not principally intended for finding rational > approximations, but I am sure that some version of the LLL algorithm > is still used. I think it means that some quadratic form in (a,b) > (where a and b are the numerator and the denominator of the rational > approximation) is (in effect) minimized but what this form is, is > not clear to me and I think it depends on the details of the > implementation. Andrzej Kozlowski >> It's rather more complicated than that. It goes roughly like this: >> given some complex number z, we want to find a polynomial f(x)= a0 >> + a1 x + a2 x^2 + ... an x^n, where ai are all integers, such that >> z is an approximate root of f. To do so we construct a certian >> quadratic form in (a0,a1,..an) involving f(z) and then use the so >> called lattice reduction algorithm of Lenstra,Lenstra and Lovasz >> (LLL) to find a vector with integral coordinates which is >> short (in some well defined sense) for this lattice. Once we have >> that we can find the required f(x), which is an approximate and, in >> favourable cases, the exact minimal polynomial of z. >> I think that it might be, in priciple, possible to do this using >> Minimize or NMinimize but I don't think it would be competitive in >> terms of performance in the former case or accuracy in the latter. >> Andrzej Kozlowski Who know which is minimalize function is used by Mathematica in > following approximation function by rational fractions: << NumberTheory`Recognize` (*In Mathematica 6 RootApproximant[] > inspite Recognize[]*) k = Recognize[N[Pi, 6], 1, x];Solve[k==0,x] if we have rational fraction p/q (where p,q are both integers) > is minimalize function: p+q, p*q, p^2+q^2 or other ? ARTUR JASINSKI > Andrzej Kozlowski pisze: >> Somehow I never saw any of this discussion so could not respond >> earlier. >> The reason why my procedure using Reduce does not work in this >> particular case, is that I forgot that Reduce will not list a >> finite >> set of solutions when it is larger than a certain bound. So, for >> example: >> cond[a_, b_] := >> Reduce[a < p/q < b && (p - 1)/q < a && p/(q - 1) > b && p >= 1 && q > = 1, {p, >> q}, Integers] >> cond[23/26, 29/30] >> Out[5]= (p == 8 && q == 9) || (p == 9 && q == 10) || >> (p == 10 && q == 11) || (p == 11 && q == 12) || >> (p == 12 && q == 13) || (p == 13 && q == 14) || >> (p == 14 && q == 15) || (p == 15 && q == 16) || >> (p == 16 && q == 17) >> (the first element gives the solution), but with a larger number of >> solutions: >> cond[113/355, 106/333] >> Out[6]= Element[p | q, Integers] && >> ((1 <= p <= 11978 && (333*p)/106 < q < >> (355*p)/113) || (11979 <= p <= 37630 && >> (333*p)/106 < q < (1/106)*(333*p + 106)) || >> (37631 <= p <= 49607 && (1/113)*(355*p - 355) < q < >> (1/106)*(333*p + 106))) >> However, the bound can be user controlled, as follows: >> Developer`SetSystemOptions[ >> ReduceOptions -> (DiscreteSolutionBound -> 10^3)] >> And then: >> First[cond[113/355, 106/333]] >> p == 219 && q == 688 >> Of course I never recommended this method, which is much slower >> than >> using Minimize. It can however find complete solutions with >> situations >> when the solution is not unique, for example if we tried to >> minimize >> the difference of squares between the denominator and the >> numerator etc. >> Andrzej Kozlowski > If we want to find rational fraction f =p/q such that > 113/355 anyone procedure proposed up to now doesn't work > good result should be > {137563,{p->13215,q->104348}} > but isn't > Your good result isn't so good, consider: >> In[36]:= 113/355 < 219/688 < 106/333 >> Out[36]= True >> One idea (similar to your Recognize approach) is to use >> Rationalize >> or >> RootApproximant with SetPrecision: >> In[71]:= Rationalize[SetPrecision[(106/333 + 113/355)/2, 6], 0] >> Out[71]= 219/688 >> In[72]:= RootApproximant[SetPrecision[(106/333 + 113/355)/2, >> 6], 1] >> Out[72]= 219/688 >> I'm not sure of the correct method to determine the precision >> to use. >> It could be something like: >> Choose largest prec such that: >> IntervalMemberQ[Interval[{lo, hi}], SetPrecision[midpoint, prec]] >> is still True. >> Carl Woll >> Wolfram Research > I should add that Daniel Lichtblau's minFraction just needs to be > tweaked a bit to find this result: minFraction[lo_Rational, hi_Rational] /; 0 < lo < hi := > Minimize[{p + q, {Denominator[lo]*p - Numerator[lo]*q > 0, > Denominator[hi]*p - Numerator[hi]*q < 0, p >= 1, q >= 1}}, {p, q}, > Integers] In[81]:= minFraction[113/355, 106/333] Out[81]= {907,{p->219,q->688}} Carl Woll > Wolfram Research > ARTUR Artur pisze: > If value p/q is known >> smallest Abs[p]+Abs[q ] should be >> << NumberTheory`Recognize` >> Recognize[p/q,1,x] >> see also >> http://www.research.att.com/~njas/sequences/A138335 >> Best wishes, >> Artur >> Curtis Osterhoudt pisze: > I doubt this is in the spirit of the problem, but if p and q > (assumed integers) aren't restricted to be _positive_, then > taking > them both to be very large negative numbers would both fit > the p/q > in I requirement, and p+q as small as possible. > C.O. > hi >> suppose that we have an interval I belong to [0,1] >> I want to know how to calculate a fraction p/q >> belong to I and p+q is the smallest possible ____ NOD32 Informacje 2701 (20071204) ____ >> Wiadomosc zostala sprawdzona przez System Antywirusowy NOD32 >> http://www.nod32.com lub http://www.nod32.pl > ____ NOD32 Informacje 2701 (20071204) ____ >> Wiadomosc zostala sprawdzona przez System Antywirusowy NOD32 >> http://www.nod32.com lub http://www.nod32.pl === Subject: Re: smallest fraction I note however that: a = RootApproximant[Pi, 1] 80143857/25510582 and Rationalize[Pi, 10^(-15)] 80143857/25510582 which are exactly the same. As far as I know Rationalize does not use lattice reduction (?) but a different algorithm, related to the way one obtains a continuous fraction expansion of Pi (at least I blieve that this is what Rationalze does). I am not sure if the fact that the same answer is returned by the above is a coincidence or it means that in fact the two algorithms amount to the same thing in this particular case ? Andrzej Kozlowski > I only realized the point of the question the day after I posted the > reply below. > I see now it is only concerned with what happens here: RootApproximant[Pi, 1] > 80143857/25510582 that with the special case when we approximate a real number by an > algebraic number of degree 1, i.e. a rational. Of course > RootApproximant is not principally intended for finding rational > approximations, but I am sure that some version of the LLL algorithm > is still used. I think it means that some quadratic form in (a,b) > (where a and b are the numerator and the denominator of the rational > approximation) is (in effect) minimized but what this form is, is > not clear to me and I think it depends on the details of the > implementation. Andrzej Kozlowski >> It's rather more complicated than that. It goes roughly like this: >> given some complex number z, we want to find a polynomial f(x)= a0 >> + a1 x + a2 x^2 + ... an x^n, where ai are all integers, such that >> z is an approximate root of f. To do so we construct a certian >> quadratic form in (a0,a1,..an) involving f(z) and then use the so >> called lattice reduction algorithm of Lenstra,Lenstra and Lovasz >> (LLL) to find a vector with integral coordinates which is >> short (in some well defined sense) for this lattice. Once we have >> that we can find the required f(x), which is an approximate and, in >> favourable cases, the exact minimal polynomial of z. >> I think that it might be, in priciple, possible to do this using >> Minimize or NMinimize but I don't think it would be competitive in >> terms of performance in the former case or accuracy in the latter. >> Andrzej Kozlowski Who know which is minimalize function is used by Mathematica in > following approximation function by rational fractions: << NumberTheory`Recognize` (*In Mathematica 6 RootApproximant[] > inspite Recognize[]*) k = Recognize[N[Pi, 6], 1, x];Solve[k==0,x] if we have rational fraction p/q (where p,q are both integers) > is minimalize function: p+q, p*q, p^2+q^2 or other ? ARTUR JASINSKI > Andrzej Kozlowski pisze: >> Somehow I never saw any of this discussion so could not respond >> earlier. >> The reason why my procedure using Reduce does not work in this >> particular case, is that I forgot that Reduce will not list a >> finite >> set of solutions when it is larger than a certain bound. So, for >> example: >> cond[a_, b_] := >> Reduce[a < p/q < b && (p - 1)/q < a && p/(q - 1) > b && p >= 1 && q > = 1, {p, >> q}, Integers] >> cond[23/26, 29/30] >> Out[5]= (p == 8 && q == 9) || (p == 9 && q == 10) || >> (p == 10 && q == 11) || (p == 11 && q == 12) || >> (p == 12 && q == 13) || (p == 13 && q == 14) || >> (p == 14 && q == 15) || (p == 15 && q == 16) || >> (p == 16 && q == 17) >> (the first element gives the solution), but with a larger number of >> solutions: >> cond[113/355, 106/333] >> Out[6]= Element[p | q, Integers] && >> ((1 <= p <= 11978 && (333*p)/106 < q < >> (355*p)/113) || (11979 <= p <= 37630 && >> (333*p)/106 < q < (1/106)*(333*p + 106)) || >> (37631 <= p <= 49607 && (1/113)*(355*p - 355) < q < >> (1/106)*(333*p + 106))) >> However, the bound can be user controlled, as follows: >> Developer`SetSystemOptions[ >> ReduceOptions -> (DiscreteSolutionBound -> 10^3)] >> And then: >> First[cond[113/355, 106/333]] >> p == 219 && q == 688 >> Of course I never recommended this method, which is much slower >> than >> using Minimize. It can however find complete solutions with >> situations >> when the solution is not unique, for example if we tried to >> minimize >> the difference of squares between the denominator and the >> numerator etc. >> Andrzej Kozlowski > If we want to find rational fraction f =p/q such that > 113/355 anyone procedure proposed up to now doesn't work > good result should be > {137563,{p->13215,q->104348}} > but isn't > Your good result isn't so good, consider: >> In[36]:= 113/355 < 219/688 < 106/333 >> Out[36]= True >> One idea (similar to your Recognize approach) is to use >> Rationalize >> or >> RootApproximant with SetPrecision: >> In[71]:= Rationalize[SetPrecision[(106/333 + 113/355)/2, 6], 0] >> Out[71]= 219/688 >> In[72]:= RootApproximant[SetPrecision[(106/333 + 113/355)/2, >> 6], 1] >> Out[72]= 219/688 >> I'm not sure of the correct method to determine the precision >> to use. >> It could be something like: >> Choose largest prec such that: >> IntervalMemberQ[Interval[{lo, hi}], SetPrecision[midpoint, prec]] >> is still True. >> Carl Woll >> Wolfram Research > I should add that Daniel Lichtblau's minFraction just needs to be > tweaked a bit to find this result: minFraction[lo_Rational, hi_Rational] /; 0 < lo < hi := > Minimize[{p + q, {Denominator[lo]*p - Numerator[lo]*q > 0, > Denominator[hi]*p - Numerator[hi]*q < 0, p >= 1, q >= 1}}, {p, q}, > Integers] In[81]:= minFraction[113/355, 106/333] Out[81]= {907,{p->219,q->688}} Carl Woll > Wolfram Research > ARTUR Artur pisze: > If value p/q is known >> smallest Abs[p]+Abs[q ] should be >> << NumberTheory`Recognize` >> Recognize[p/q,1,x] >> see also >> http://www.research.att.com/~njas/sequences/A138335 >> Best wishes, >> Artur >> Curtis Osterhoudt pisze: > I doubt this is in the spirit of the problem, but if p and q > (assumed integers) aren't restricted to be _positive_, then > taking > them both to be very large negative numbers would both fit > the p/q > in I requirement, and p+q as small as possible. > C.O. > hi >> suppose that we have an interval I belong to [0,1] >> I want to know how to calculate a fraction p/q >> belong to I and p+q is the smallest possible ____ NOD32 Informacje 2701 (20071204) ____ >> Wiadomosc zostala sprawdzona przez System Antywirusowy NOD32 >> http://www.nod32.com lub http://www.nod32.pl > ____ NOD32 Informacje 2701 (20071204) ____ >> Wiadomosc zostala sprawdzona przez System Antywirusowy NOD32 >> http://www.nod32.com lub http://www.nod32.pl === Subject: Re: smallest fraction I only realized the point of the question the day after I posted the reply below. I see now it is only concerned with what happens here: RootApproximant[Pi, 1] 80143857/25510582 that with the special case when we approximate a real number by an algebraic number of degree 1, i.e. a rational. Of course RootApproximant is not principally intended for finding rational approximations, but I am sure that some version of the LLL algorithm is still used. I think it means that some quadratic form in (a,b) (where a and b are the numerator and the denominator of the rational approximation) is (in effect) minimized but what this form is, is not clear to me and I think it depends on the details of the implementation. Andrzej Kozlowski > It's rather more complicated than that. It goes roughly like this: > given some complex number z, we want to find a polynomial f(x)= a0 + > a1 x + a2 x^2 + ... an x^n, where ai are all integers, such that z > is an approximate root of f. To do so we construct a certian > quadratic form in (a0,a1,..an) involving f(z) and then use the so > called lattice reduction algorithm of Lenstra,Lenstra and Lovasz > (LLL) to find a vector with integral coordinates which is > short (in some well defined sense) for this lattice. Once we have > that we can find the required f(x), which is an approximate and, in > favourable cases, the exact minimal polynomial of z. I think that it might be, in priciple, possible to do this using > Minimize or NMinimize but I don't think it would be competitive in > terms of performance in the former case or accuracy in the latter. Andrzej Kozlowski >> Who know which is minimalize function is used by Mathematica in >> following approximation function by rational fractions: >> << NumberTheory`Recognize` (*In Mathematica 6 RootApproximant[] >> inspite Recognize[]*) >> k = Recognize[N[Pi, 6], 1, x];Solve[k==0,x] >> if we have rational fraction p/q (where p,q are both integers) >> is minimalize function: p+q, p*q, p^2+q^2 or other ? >> ARTUR JASINSKI >> Andrzej Kozlowski pisze: > Somehow I never saw any of this discussion so could not respond > earlier. The reason why my procedure using Reduce does not work in this > particular case, is that I forgot that Reduce will not list a finite > set of solutions when it is larger than a certain bound. So, for > example: cond[a_, b_] := > Reduce[a < p/q < b && (p - 1)/q < a && p/(q - 1) > b && p >= 1 && q >> = 1, {p, > q}, Integers] cond[23/26, 29/30] > Out[5]= (p == 8 && q == 9) || (p == 9 && q == 10) || > (p == 10 && q == 11) || (p == 11 && q == 12) || > (p == 12 && q == 13) || (p == 13 && q == 14) || > (p == 14 && q == 15) || (p == 15 && q == 16) || > (p == 16 && q == 17) > (the first element gives the solution), but with a larger number of > solutions: cond[113/355, 106/333] > Out[6]= Element[p | q, Integers] && > ((1 <= p <= 11978 && (333*p)/106 < q < > (355*p)/113) || (11979 <= p <= 37630 && > (333*p)/106 < q < (1/106)*(333*p + 106)) || > (37631 <= p <= 49607 && (1/113)*(355*p - 355) < q < > (1/106)*(333*p + 106))) However, the bound can be user controlled, as follows: Developer`SetSystemOptions[ > ReduceOptions -> (DiscreteSolutionBound -> 10^3)] And then: First[cond[113/355, 106/333]] > p == 219 && q == 688 > Of course I never recommended this method, which is much slower than > using Minimize. It can however find complete solutions with > situations > when the solution is not unique, for example if we tried to minimize > the difference of squares between the denominator and the > numerator etc. Andrzej Kozlowski > If we want to find rational fraction f =p/q such that >> 113/355> anyone procedure proposed up to now doesn't work >> good result should be >> {137563,{p->13215,q->104348}} >> but isn't > Your good result isn't so good, consider: In[36]:= 113/355 < 219/688 < 106/333 Out[36]= True One idea (similar to your Recognize approach) is to use > Rationalize > or > RootApproximant with SetPrecision: In[71]:= Rationalize[SetPrecision[(106/333 + 113/355)/2, 6], 0] Out[71]= 219/688 In[72]:= RootApproximant[SetPrecision[(106/333 + 113/355)/2, 6], > 1] Out[72]= 219/688 I'm not sure of the correct method to determine the precision to > use. > It could be something like: Choose largest prec such that: IntervalMemberQ[Interval[{lo, hi}], SetPrecision[midpoint, prec]] is still True. Carl Woll > Wolfram Research > I should add that Daniel Lichtblau's minFraction just needs to be >> tweaked a bit to find this result: >> minFraction[lo_Rational, hi_Rational] /; 0 < lo < hi := >> Minimize[{p + q, {Denominator[lo]*p - Numerator[lo]*q > 0, >> Denominator[hi]*p - Numerator[hi]*q < 0, p >= 1, q >= 1}}, {p, q}, >> Integers] >> In[81]:= minFraction[113/355, 106/333] >> Out[81]= {907,{p->219,q->688}} >> Carl Woll >> Wolfram Research >> ARTUR >> Artur pisze: > If value p/q is known > smallest Abs[p]+Abs[q ] should be > << NumberTheory`Recognize` > Recognize[p/q,1,x] see also > http://www.research.att.com/~njas/sequences/A138335 Best wishes, > Artur Curtis Osterhoudt pisze: >> I doubt this is in the spirit of the problem, but if p and q >> (assumed integers) aren't restricted to be _positive_, then >> taking >> them both to be very large negative numbers would both fit >> the p/q >> in I requirement, and p+q as small as possible. >> C.O. > hi suppose that we have an interval I belong to [0,1] I want to know how to calculate a fraction p/q > belong to I and p+q is the smallest possible > ____ NOD32 Informacje 2701 (20071204) ____ Wiadomosc zostala sprawdzona przez System Antywirusowy NOD32 > http://www.nod32.com lub http://www.nod32.pl > > ____ NOD32 Informacje 2701 (20071204) ____ Wiadomosc zostala sprawdzona przez System Antywirusowy NOD32 > http://www.nod32.com lub http://www.nod32.pl > === Subject: Re: smallest fraction It's rather more complicated than that. It goes roughly like this: given some complex number z, we want to find a polynomial f(x)= a0 + a1 x + a2 x^2 + ... an x^n, where ai are all integers, such that z is an approximate root of f. To do so we construct a certian quadratic form in (a0,a1,..an) involving f(z) and then use the so called lattice reduction algorithm of Lenstra,Lenstra and Lovasz (LLL) to find a vector with integral coordinates which is short (in some well defined sense) for this lattice. Once we have that we can find the required f(x), which is an approximate and, in favourable cases, the exact minimal polynomial of z. I think that it might be, in priciple, possible to do this using Minimize or NMinimize but I don't think it would be competitive in terms of performance in the former case or accuracy in the latter. Andrzej Kozlowski Who know which is minimalize function is used by Mathematica in > following approximation function by rational fractions: << NumberTheory`Recognize` (*In Mathematica 6 RootApproximant[] > inspite Recognize[]*) k = Recognize[N[Pi, 6], 1, x];Solve[k==0,x] if we have rational fraction p/q (where p,q are both integers) > is minimalize function: p+q, p*q, p^2+q^2 or other ? ARTUR JASINSKI > Andrzej Kozlowski pisze: >> Somehow I never saw any of this discussion so could not respond >> earlier. >> The reason why my procedure using Reduce does not work in this >> particular case, is that I forgot that Reduce will not list a finite >> set of solutions when it is larger than a certain bound. So, for >> example: >> cond[a_, b_] := >> Reduce[a < p/q < b && (p - 1)/q < a && p/(q - 1) > b && p >= 1 && q > = 1, {p, >> q}, Integers] >> cond[23/26, 29/30] >> Out[5]= (p == 8 && q == 9) || (p == 9 && q == 10) || >> (p == 10 && q == 11) || (p == 11 && q == 12) || >> (p == 12 && q == 13) || (p == 13 && q == 14) || >> (p == 14 && q == 15) || (p == 15 && q == 16) || >> (p == 16 && q == 17) >> (the first element gives the solution), but with a larger number of >> solutions: >> cond[113/355, 106/333] >> Out[6]= Element[p | q, Integers] && >> ((1 <= p <= 11978 && (333*p)/106 < q < >> (355*p)/113) || (11979 <= p <= 37630 && >> (333*p)/106 < q < (1/106)*(333*p + 106)) || >> (37631 <= p <= 49607 && (1/113)*(355*p - 355) < q < >> (1/106)*(333*p + 106))) >> However, the bound can be user controlled, as follows: >> Developer`SetSystemOptions[ >> ReduceOptions -> (DiscreteSolutionBound -> 10^3)] >> And then: >> First[cond[113/355, 106/333]] >> p == 219 && q == 688 >> Of course I never recommended this method, which is much slower than >> using Minimize. It can however find complete solutions with >> situations >> when the solution is not unique, for example if we tried to minimize >> the difference of squares between the denominator and the numerator >> etc. >> Andrzej Kozlowski > If we want to find rational fraction f =p/q such that > 113/355 anyone procedure proposed up to now doesn't work > good result should be > {137563,{p->13215,q->104348}} > but isn't > Your good result isn't so good, consider: >> In[36]:= 113/355 < 219/688 < 106/333 >> Out[36]= True >> One idea (similar to your Recognize approach) is to use Rationalize >> or >> RootApproximant with SetPrecision: >> In[71]:= Rationalize[SetPrecision[(106/333 + 113/355)/2, 6], 0] >> Out[71]= 219/688 >> In[72]:= RootApproximant[SetPrecision[(106/333 + 113/355)/2, 6], 1] >> Out[72]= 219/688 >> I'm not sure of the correct method to determine the precision to >> use. >> It could be something like: >> Choose largest prec such that: >> IntervalMemberQ[Interval[{lo, hi}], SetPrecision[midpoint, prec]] >> is still True. >> Carl Woll >> Wolfram Research > I should add that Daniel Lichtblau's minFraction just needs to be > tweaked a bit to find this result: minFraction[lo_Rational, hi_Rational] /; 0 < lo < hi := > Minimize[{p + q, {Denominator[lo]*p - Numerator[lo]*q > 0, > Denominator[hi]*p - Numerator[hi]*q < 0, p >= 1, q >= 1}}, {p, q}, > Integers] In[81]:= minFraction[113/355, 106/333] Out[81]= {907,{p->219,q->688}} Carl Woll > Wolfram Research > ARTUR Artur pisze: > If value p/q is known >> smallest Abs[p]+Abs[q ] should be >> << NumberTheory`Recognize` >> Recognize[p/q,1,x] >> see also >> http://www.research.att.com/~njas/sequences/A138335 >> Best wishes, >> Artur >> Curtis Osterhoudt pisze: > I doubt this is in the spirit of the problem, but if p and q > (assumed integers) aren't restricted to be _positive_, then > taking > them both to be very large negative numbers would both fit the > p/q > in I requirement, and p+q as small as possible. > C.O. > hi >> suppose that we have an interval I belong to [0,1] >> I want to know how to calculate a fraction p/q >> belong to I and p+q is the smallest possible ____ NOD32 Informacje 2701 (20071204) ____ >> Wiadomosc zostala sprawdzona przez System Antywirusowy NOD32 >> http://www.nod32.com lub http://www.nod32.pl > ____ NOD32 Informacje 2701 (20071204) ____ >> Wiadomosc zostala sprawdzona przez System Antywirusowy NOD32 >> http://www.nod32.com lub http://www.nod32.pl > === Subject: Re: smallest fraction Who know which is minimalize function is used by Mathematica in following approximation function by rational fractions: << NumberTheory`Recognize` (*In Mathematica 6 RootApproximant[] inspite Recognize[]*) k = Recognize[N[Pi, 6], 1, x];Solve[k==0,x] if we have rational fraction p/q (where p,q are both integers) is minimalize function: p+q, p*q, p^2+q^2 or other ? ARTUR JASINSKI Andrzej Kozlowski pisze: > Somehow I never saw any of this discussion so could not respond earlier. The reason why my procedure using Reduce does not work in this > particular case, is that I forgot that Reduce will not list a finite > set of solutions when it is larger than a certain bound. So, for > example: cond[a_, b_] := > Reduce[a < p/q < b && (p - 1)/q < a && p/(q - 1) > b && p >= 1 && q >= 1, {p, > q}, Integers] cond[23/26, 29/30] > Out[5]= (p == 8 && q == 9) || (p == 9 && q == 10) || > (p == 10 && q == 11) || (p == 11 && q == 12) || > (p == 12 && q == 13) || (p == 13 && q == 14) || > (p == 14 && q == 15) || (p == 15 && q == 16) || > (p == 16 && q == 17) > (the first element gives the solution), but with a larger number of > solutions: cond[113/355, 106/333] > Out[6]= Element[p | q, Integers] && > ((1 <= p <= 11978 && (333*p)/106 < q < > (355*p)/113) || (11979 <= p <= 37630 && > (333*p)/106 < q < (1/106)*(333*p + 106)) || > (37631 <= p <= 49607 && (1/113)*(355*p - 355) < q < > (1/106)*(333*p + 106))) However, the bound can be user controlled, as follows: Developer`SetSystemOptions[ > ReduceOptions -> (DiscreteSolutionBound -> 10^3)] And then: First[cond[113/355, 106/333]] > p == 219 && q == 688 > Of course I never recommended this method, which is much slower than > using Minimize. It can however find complete solutions with situations > when the solution is not unique, for example if we tried to minimize > the difference of squares between the denominator and the numerator etc. Andrzej Kozlowski > >> >> If we want to find rational fraction f =p/q such that >> 113/355> anyone procedure proposed up to now doesn't work >> good result should be >> {137563,{p->13215,q->104348}} >> but isn't >> > Your good result isn't so good, consider: In[36]:= 113/355 < 219/688 < 106/333 Out[36]= True One idea (similar to your Recognize approach) is to use Rationalize > or > RootApproximant with SetPrecision: In[71]:= Rationalize[SetPrecision[(106/333 + 113/355)/2, 6], 0] Out[71]= 219/688 In[72]:= RootApproximant[SetPrecision[(106/333 + 113/355)/2, 6], 1] Out[72]= 219/688 I'm not sure of the correct method to determine the precision to use. > It could be something like: Choose largest prec such that: IntervalMemberQ[Interval[{lo, hi}], SetPrecision[midpoint, prec]] is still True. Carl Woll > Wolfram Research > >> I should add that Daniel Lichtblau's minFraction just needs to be >> tweaked a bit to find this result: >> minFraction[lo_Rational, hi_Rational] /; 0 < lo < hi := >> Minimize[{p + q, {Denominator[lo]*p - Numerator[lo]*q > 0, >> Denominator[hi]*p - Numerator[hi]*q < 0, p >= 1, q >= 1}}, {p, q}, >> Integers] >> In[81]:= minFraction[113/355, 106/333] >> Out[81]= {907,{p->219,q->688}} >> Carl Woll >> Wolfram Research >> >> ARTUR >> Artur pisze: >> > If value p/q is known > smallest Abs[p]+Abs[q ] should be > << NumberTheory`Recognize` > Recognize[p/q,1,x] see also > http://www.research.att.com/~njas/sequences/A138335 Best wishes, > Artur Curtis Osterhoudt pisze: >> I doubt this is in the spirit of the problem, but if p and q >> (assumed integers) aren't restricted to be _positive_, then taking >> them both to be very large negative numbers would both fit the p/q >> in I requirement, and p+q as small as possible. >> C.O. >> > hi suppose that we have an interval I belong to [0,1] I want to know how to calculate a fraction p/q > belong to I and p+q is the smallest possible >> > ____ NOD32 Informacje 2701 (20071204) ____ Wiadomosc zostala sprawdzona przez System Antywirusowy NOD32 > http://www.nod32.com lub http://www.nod32.pl > > >> ____ NOD32 Informacje 2701 (20071204) ____ Wiadomosc zostala sprawdzona przez System Antywirusowy NOD32 > http://www.nod32.com lub http://www.nod32.pl === Subject: Re: smallest Somehow I never saw any of this discussion so could not respond earlier. The reason why my procedure using Reduce does not work in this particular case, is that I forgot that Reduce will not list a finite set of solutions when it is larger than a certain bound. So, for example: cond[a_, b_] := Reduce[a < p/q < b && (p - 1)/q < a && p/(q - 1) > b && p >= 1 && q >= 1, {p, q}, Integers] cond[23/26, 29/30] Out[5]= (p == 8 && q == 9) || (p == 9 && q == 10) || (p == 10 && q == 11) || (p == 11 && q == 12) || (p == 12 && q == 13) || (p == 13 && q == 14) || (p == 14 && q == 15) || (p == 15 && q == 16) || (p == 16 && q == 17) (the first element gives the solution), but with a larger number of solutions: cond[113/355, 106/333] Out[6]= Element[p | q, Integers] && ((1 <= p <= 11978 && (333*p)/106 < q < (355*p)/113) || (11979 <= p <= 37630 && (333*p)/106 < q < (1/106)*(333*p + 106)) || (37631 <= p <= 49607 && (1/113)*(355*p - 355) < q < (1/106)*(333*p + 106))) However, the bound can be user controlled, as follows: Developer`SetSystemOptions[ ReduceOptions -> (DiscreteSolutionBound -> 10^3)] And then: First[cond[113/355, 106/333]] p == 219 && q == 688 Of course I never recommended this method, which is much slower than using Minimize. It can however find complete solutions with situations when the solution is not unique, for example if we tried to minimize the difference of squares between the denominator and the numerator etc. Andrzej Kozlowski If we want to find rational fraction f =p/q such that > 113/355 anyone procedure proposed up to now doesn't work > good result should be > {137563,{p->13215,q->104348}} > but isn't >> Your good result isn't so good, consider: >> In[36]:= 113/355 < 219/688 < 106/333 >> Out[36]= True >> One idea (similar to your Recognize approach) is to use Rationalize >> or >> RootApproximant with SetPrecision: >> In[71]:= Rationalize[SetPrecision[(106/333 + 113/355)/2, 6], 0] >> Out[71]= 219/688 >> In[72]:= RootApproximant[SetPrecision[(106/333 + 113/355)/2, 6], 1] >> Out[72]= 219/688 >> I'm not sure of the correct method to determine the precision to use. >> It could be something like: >> Choose largest prec such that: >> IntervalMemberQ[Interval[{lo, hi}], SetPrecision[midpoint, prec]] >> is still True. >> Carl Woll >> Wolfram Research I should add that Daniel Lichtblau's minFraction just needs to be > tweaked a bit to find this result: minFraction[lo_Rational, hi_Rational] /; 0 < lo < hi := > Minimize[{p + q, {Denominator[lo]*p - Numerator[lo]*q > 0, > Denominator[hi]*p - Numerator[hi]*q < 0, p >= 1, q >= 1}}, {p, q}, > Integers] In[81]:= minFraction[113/355, 106/333] Out[81]= {907,{p->219,q->688}} Carl Woll > Wolfram Research ARTUR Artur pisze: >> If value p/q is known >> smallest Abs[p]+Abs[q ] should be >> << NumberTheory`Recognize` >> Recognize[p/q,1,x] >> see also >> http://www.research.att.com/~njas/sequences/A138335 >> Best wishes, >> Artur >> Curtis Osterhoudt pisze: > I doubt this is in the spirit of the problem, but if p and q > (assumed integers) aren't restricted to be _positive_, then taking > them both to be very large negative numbers would both fit the p/q > in I requirement, and p+q as small as possible. > C.O. >> hi >> suppose that we have an interval I belong to [0,1] >> I want to know how to calculate a fraction p/q >> belong to I and p+q is the smallest possible > >> ____ NOD32 Informacje 2701 (20071204) ____ >> Wiadomosc zostala sprawdzona przez System Antywirusowy NOD32 >> http://www.nod32.com lub http://www.nod32.pl > === Subject: Re: smallest > If we want to find rational fraction f =p/q such that >> 113/355> anyone procedure proposed up to now doesn't work >> good result should be >> {137563,{p->13215,q->104348}} >> but isn't >Your good result isn't so good, consider: In[36]:= 113/355 < 219/688 < 106/333 Out[36]= True One idea (similar to your Recognize approach) is to use Rationalize or > RootApproximant with SetPrecision: In[71]:= Rationalize[SetPrecision[(106/333 + 113/355)/2, 6], 0] Out[71]= 219/688 In[72]:= RootApproximant[SetPrecision[(106/333 + 113/355)/2, 6], 1] Out[72]= 219/688 I'm not sure of the correct method to determine the precision to use. > It could be something like: Choose largest prec such that: IntervalMemberQ[Interval[{lo, hi}], SetPrecision[midpoint, prec]] is still True. Carl Woll > Wolfram Research I should add that Daniel Lichtblau's minFraction just needs to be tweaked a bit to find this result: minFraction[lo_Rational, hi_Rational] /; 0 < lo < hi := Minimize[{p + q, {Denominator[lo]*p - Numerator[lo]*q > 0, Denominator[hi]*p - Numerator[hi]*q < 0, p >= 1, q >= 1}}, {p, q}, Integers] In[81]:= minFraction[113/355, 106/333] Out[81]= {907,{p->219,q->688}} Carl Woll Wolfram Research > ARTUR >> Artur pisze: >If value p/q is known > smallest Abs[p]+Abs[q ] should be > << NumberTheory`Recognize` > Recognize[p/q,1,x] see also > http://www.research.att.com/~njas/sequences/A138335 Best wishes, > Artur Curtis Osterhoudt pisze: > I doubt this is in the spirit of the problem, but if p and q >> (assumed integers) aren't restricted to be _positive_, then taking >> them both to be very large negative numbers would both fit the p/q >> in I requirement, and p+q as small as possible. >> C.O. >> >> > hi suppose that we have an interval I belong to [0,1] I want to know how to calculate a fraction p/q > belong to I and p+q is the smallest possible > >> >> ____ NOD32 Informacje 2701 (20071204) ____ Wiadomosc zostala sprawdzona przez System Antywirusowy NOD32 > http://www.nod32.com lub http://www.nod32.pl === Subject: Re: smallest >If we want to find rational fraction f =p/q such that 113/355and sum p+q is minimal >anyone procedure proposed up to now doesn't work >good result should be >{137563,{p->13215,q->104348}} >but isn't > > Your good result isn't so good, consider: In[36]:= 113/355 < 219/688 < 106/333 Out[36]= True One idea (similar to your Recognize approach) is to use Rationalize or RootApproximant with SetPrecision: In[71]:= Rationalize[SetPrecision[(106/333 + 113/355)/2, 6], 0] Out[71]= 219/688 In[72]:= RootApproximant[SetPrecision[(106/333 + 113/355)/2, 6], 1] Out[72]= 219/688 I'm not sure of the correct method to determine the precision to use. It could be something like: Choose largest prec such that: IntervalMemberQ[Interval[{lo, hi}], SetPrecision[midpoint, prec]] is still True. Carl Woll Wolfram Research >ARTUR Artur pisze: > >If value p/q is known >>smallest Abs[p]+Abs[q ] should be >><< NumberTheory`Recognize` >>Recognize[p/q,1,x] >>see also >>http://www.research.att.com/~njas/sequences/A138335 >>Best wishes, >>Artur >>Curtis Osterhoudt pisze: >> >> > I doubt this is in the spirit of the problem, but if p and q (assumed >integers) aren't restricted to be _positive_, then taking them both to be >very large negative numbers would both fit the p/q in I requirement, and p+q >as small as possible. C.O. > > >hi >>suppose that we have an interval I belong to [0,1] >>I want to know how to calculate a fraction p/q >>belong to I and p+q is the smallest possible >> >> >> > >____ NOD32 Informacje 2701 (20071204) ____ >>Wiadomosc zostala sprawdzona przez System Antywirusowy NOD32 >>http://www.nod32.com lub http://www.nod32.pl >> >> >> === Subject: Re: smallest > If we want to find rational fraction f =p/q such that 113/355 and sum p+q is minimal > anyone procedure proposed up to now doesn't work > good result should be > {137563,{p->13215,q->104348}} > but isn't > ARTUR You can use continued fractions to get a contender, as below. In[8]:= ContinuedFraction[355/113] Out[8]= {3, 7, 16} In[15]:= ContinuedFraction[333/106] Out[15]= {3, 7, 15} What this suggest is that a plausible result might be obtained by splitting the difference on the last convergent: 1/(3+ 1/(7+ 2/31))) This yields 219/688. That happens to agree with Minimize: In[17]:= Minimize[{p+q, {355*p>113*q,333*p<106*q,p>=1,q>=1}}, {p,q}, Integers] Out[17]= {907, {p -> 219, q -> 688}} I notice that 907 is considerably smaller than 137563. Daniel Lichtblau Wolfram Research === Subject: Re: smallest fraction If we want to find rational fraction f =p/q such that 113/35513215,q->104348}} but isn't ARTUR Artur pisze: > If value p/q is known > smallest Abs[p]+Abs[q ] should be > << NumberTheory`Recognize` > Recognize[p/q,1,x] see also > http://www.research.att.com/~njas/sequences/A138335 Best wishes, > Artur Curtis Osterhoudt pisze: > >> I doubt this is in the spirit of the problem, but if p and q (assumed >> integers) aren't restricted to be _positive_, then taking them both to be >> very large negative numbers would both fit the p/q in I requirement, and p+q >> as small as possible. >> C.O. >> >> > hi suppose that we have an interval I belong to [0,1] I want to know how to calculate a fraction p/q > belong to I and p+q is the smallest possible > > >> >> > ____ NOD32 Informacje 2701 (20071204) ____ Wiadomosc zostala sprawdzona przez System Antywirusowy NOD32 > http://www.nod32.com lub http://www.nod32.pl === Subject: Re: symbolic evaluation Paul:( === Subject: Re: symbolic evaluation You must have missed my previous reply. See http://forums.wolfram.com/mathgroup/archive/2008/Mar/msg00912.html So, what about using HoldForm as in, In[1]:= Reduce[7 x == HoldForm@14] Out[1]= 14 x == -- 7 -- === Subject: Re: symbolic evaluation You're still stubbornly confusing two basically different things in Mathematica... a = b is NOT an equation in Mathematica! It is an abbreviation for Set[a,b], which immediately gives a the value of b. 7x = 14 (* syntactically forbidden; error message results *) a == b (with TWO equal signs) is an equation in Mathematica, which may have the value True or False (in case Mathematica has sufficient information already about a and b to decide this) or just return the equation if it cannot yet decide the truth or falsity. 7x == 14 (* input *) 7x == 14 (* output result *) You really want to transform the equation 7x==14 into the equation x==2? Easy: Reduce[7x == 14, x] (* input *) x == 2 (* output *) Under ordinary circumstances, you would not want to transform your equation into the form you say. > Paul:( > -- Murray Eisenberg murray@math.umass.edu Mathematics & Statistics Dept. Lederle Graduate Research Tower phone 413 549-1020 (H) University of Massachusetts 413 545-2859 (W) 710 North Pleasant Street fax 413 545-1801 Amherst, MA 01003-9305 === Subject: Re: symbolic evaluation > the equation and giving the answer 2, which is not what I need. > What I need is for Mathematica to transpose the formula giving as > out put x = 14/7. I'm really wondering why you need Mathematica to do that :-) > I beginning to believe that mathematica can't do it > because the designer didn't put that capability in it. Being a full blown programming language, there isn't too much that it can't do, you just need to tell it what you want... > This must be a hard concept for a computer to do. the problem here is that mathematica knows about rationals, and that 2 is a simpler and mathematically fully equivalent form of 14/7. > It just seems simple to me. What's wrong with > out[1]= {{x -> 14/2}} Which output I can't seem to get. nothing wrong with it, but in just every case I can think of, it makes sense to simplify this. For all but the most trivial cases you would end up with incredible large fractions. Also many of the internals of mathematica require expressions to be turned into some standard form, e.g. to recognize that two expressions are equal. So basically I think it is for practical and performance reasons that simplifying rationals is automatic. If you want mathematica to not use it's internal knowledge about rationals, you could try to mask the fact that it deals with integers, e.g. by turning them into strings: Solve[7x==14 /. i_Integer:>ToString[i],x] For a real application (still wondering what that would be...) using a more sophisticated way to mask numbers is probably even better: In[25]:= reseq=Equal@@Solve[7 x==14/.i_Integer:>HoldForm[i],x][[1,1]] Out[25]= x==14/7 then when the need arises you can switch back to the normal behaviour: In[26]:= ReleaseHold[reseq] Out[26]= x==2 If I could convince you that mathematica probably can do what you need but you don't understand the details I would strongly suggest to read as much from the documentation as you can digest, but at least look at: tutorial/Evaluation (type this into the navigation bar of the documentation center). Maybe it would also help to describe in more details what exactly you are trying to do, my guess is that your actual problem is somewhat more complicated than what you have posted, otherwise the use of mathematica would be a terrible waste of money and time (cpu and yours) hth, albert === Subject: Re: symbolic evaluation > solving the equation and giving the answer 2, which is not what I > need. What I need is for Mathematica to transpose the formula giving > as out put x = 14/7. I beginning to believe that mathematica can't do > it because the designer didn't put that capability in it. This must > be a hard concept for a computer to do. It just seems simple to me. > What's wrong with out[1]= {{x -> 14/2}} Which output I can't seem > to get. > Paul:( :-) Symbolize e.g as digit string to avoid the trivial evaluation simplifications in: Solve[7 x == 14, x] out: {{x -> 14/7}} If there are many numbers you may use the rule equation/. a_?NumberQ :> ToString[a] -- Roland Franzius === Subject: Re: symbolic evaluation 14/7 is the same as 2. If you want to keep Mathematica from evaluating expressions, use Hold, or HoldForm: Hold[14/7] HoldForm[14/7] I can't see why anyone would need to get the solution in the form 14/7 instead of 2. This is just a minor formatting difference, not a mathematical one. If you need this for teaching elementary mathematics, then I think that a blackboard is a much more suitable tool than Mathematica ... === Subject: Re: Another stylesheet question > I went thru the stylesheet tutorial that David Park kindly >> made available. I was successful in making the new >> stylesheet he proposed. But I'd like to do something he >> didn't cover (that I could find). >> I'd like to simply change the size of the text in the text >> style (the cell type found in the little box at upper left >> in a notebook). I can reformat the text cell by cell but I'd >> like it to just use a proper text size to start with from >> default.nb. I've given up trying to do this in Options >> Inspector. I've looked thru it forever and can't find any >> way to change text size. And if I did, would that change >> what's in the default.nb stylesheet? >> So I did Format/ Edit Stylesheet, selected the text style, >> to modify, then changed it to a new size and color via the >> Format Menu and then *Save As* default.nb. Well, that >> didn't work -- Mathematica wouldn't even run on restart. I had to >> restore default.nb from my backup copy. Even though the Edit >> Stylesheet window says it is using inherited base >> definitions from default.nb, the file it makes is tiny and >> apparently leaves out items needed for Mathematica to run. >> So I'm missing the big picture -- can someone please tell me >> how to modify default.nb -- or make Mathematica use a different Hi Jerry, You should give the altered notebook a new name, eg. jerrystyle.nb > and place it somewhere in > $UserBaseDirectory/SystemFiles/FrontEnd/Stylesheets. > Your style will now appear in the Format/Stylesheet selection. > In the options inspector search for DefaultStyleDefinitions and set > them to the full path to your new stylesheet to make it the default. Gruss Peter Actually, you can put it in the location you specify, but call it Default.nb. Then you don't have to change the DefaultStyleDefinitions. John Fultz jfultz@wolfram.com User Interface Group Wolfram Research, Inc. === Subject: variance of product of 2 independent variables Hello Ben - I have a question about the subject matter. To review, you sent Frank Brand the following: < - < ab >^2 = - ^2^2 = v(a) + v(b) + v(a)v(b); v(a)=-^2, v(b)=-^2 here v(.) denotes variance, <.> denotes mean. Note that we do not have to assume normal distributions for a and b, essential is that their are uncorrelated, hence the means of products factor into products of means.>> If = 1000 and = 0.001, and v(a) = 100 and v(b) = 1e-10 (in other words, both a and b have 1% standard deviations), then I compute v(ab) = 100*0.001 + 1e-10*1000 + 100*1e-10 ~ 0.1 which is obviously wrong ( = 1.000 and std deviation would be sqrt(0.1) = 0.31. Help! Da stimmt was nicht! Rudy dankwort Phoenix AZ USA === Subject: Re: Problems with differentiating Piecewise functions You can eliminate the gap in the Plot by excluding 50 Plot[pw[x], {x, 0, 100}, Exclusions -> 50] For numerical analysis, Rationalize the expressions and make them exactly equal, i.e., slight correction to one or both expressions to make them exactly equal at the join. Bob Hanlon If I set up a piecewise function and differentiate it: In[112]:= pw1 = Piecewise[{{x^2, x <= 0}, {x, x > 0}}] Out[112]= [Piecewise] { > {x^2, x <= 0}, > {x, x > 0} > } In[113]:= pw1 /. x -> 0 Out[113]= 0 In[114]:= pw1d = D[pw1, x] Out[114]= [Piecewise] { > {2 x, x < 0}, > {1, x > 0}, > {Indeterminate, !(* > TagBox[True, > PiecewiseDefault, > AutoDelete->False, > DeletionWarning->True])} > } In[115]:= pw1d /. x -> 0 Out[115]= Indeterminate Then at the joins between the pieces I get Indeterminate values, > because the limit x <= 0 has become x < 0 after differentiation. Does > anyone know a solution to this problem? > Howard. What do you mean by a solution to this problem? You have a > function that is not differentiable at 0 and you would like it's > derivative to have a value there? You can't expect a solution to a > problem when you do not tell us what is the problem (except the fact > that not all functions are differentiable - but that's life). > Note that is your pieceise function is actually differentiable than > the derivative is defined everywhere: pw2 = Piecewise[{{x^2, x <= 0}, {x^3, x > 0}}]; pw2d = D[pw2, x] > Piecewise[{{2*x, x < 0}, {0, x == 0}}, 3*x^2] This is also as it should be. What else would you expect? Andrzej Kozlowski example that I posted (I simplified my problem by cutting and pasting > an example from the help file to keep the post short). I am actually > fitting cubic splines and the functions are continuous up to the > second derivative (at least to the accuracy of machine precision). A > better example is: In[54]:= pw[x_] := > Piecewise[{{0.+ 0.007508378277320685 x + 7.561460342471517*10^-7 x^3, > x < 50}, {-4.8729206849430454*10^-6 (-125.76959597633721 + > x) (1148.1044516606876- 47.50636365246156 x + x^2), 50 <= x}}] In[55]:= pw[x] Out[55]= [Piecewise] { > {0.+ 0.00750838 x + 7.56146*10^-7 x^3, x < 50}, > {-4.87292*10^-6 (-125.77 + x) (1148.1- 47.5064 x + x^2), 50 <= x} > } In[56]:= pw[50] Out[56]= 0.469937 In[57]:= pw[50 + 10^-30] Out[57]= 0.469937 In[58]:= pw[50 - 10^-30] Out[58]= 0.469937 In[60]:= pw'[x] Out[60]= [Piecewise] { > {0.00750838+ 2.26844*10^-6 x^2, x < 50}, > {-4.87292*10^-6 (-125.77 + x) (-47.5064 + 2 x) - > 4.87292*10^-6 (1148.1- 47.5064 x + x^2), x > 50}, > {Indeterminate, !(* > TagBox[True, > PiecewiseDefault, > AutoDelete->False, > DeletionWarning->True])} > } In[61]:= pw'[50] Out[61]= Indeterminate In[62]:= pw'[50 + 10^-30] Out[62]= 0.0131795 In[63]:= pw'[50 - 10^-30] Out[63]= 0.0131795 Also if you Plot pw or pw' you get an annoying gap in the plot at the > join (but strangely not pw''). My guess is that Mathematica is too > pedantic about machine precision and is treating each piece as an > algebraic equation. However this does not explain why Plot behaves > funnily and doesn't help if you are trying to do numerical analysis. > === Subject: Re: changing >But how do I get GraphPlot to use labels that _I_ specify, rather than >numbers -- when using a graph created with Combinatorica and without >having to directly specify the labels as part of the graph structure. For example: g=Cycle[6]; GraphPlot[g, > VertexLabeling->True,VertexRenderingFunction->(Text[...]&)] This sort of thing doesn't produce any vertex labels even if I first use >something like: g = SetGraphOptions[g, VertexLabel -> Characters[b,a,f,e,d,c]]; > > The VertexLabel option can take Boolean values only. Perhaps you meant: g = SetVertexLabels[Cycle[6], {b,a,f,e,d,c}]; GraphPlot[g, VertexLabeling -> True] Carl Woll Wolfram Research >(Comment: The documentation about graph display is really atrociously >inadequate!) > >Yes, GraphPlot seems to permit making nice vertices (or edges), but then >the labeling -- either with a Graph object from Combinatorica or just >the kind of graph described by the GraphPlot reference page -- does not >seem to admit vertex labels or edge labels, at least so far as I can >see. For example, neither of the following displays either vertex >labels or edge labels: >GraphPlot[Cycle[3], Method -> Automatic, VertexLabeling -> True, > EdgeLabeling -> True, EdgeRenderingFunction -> ({Black, Line[#1]} &), > VertexRenderingFunction -> ({EdgeForm[{Thickness[0.005], Red}], > Yellow, Disk[#1, 0.04]} &)] GraphPlot[{{v1 -> v2, a}, {v2 -> v3, b}, {v3 -> v1, c}}, > Method -> Automatic, VertexLabeling -> True, EdgeLabeling -> True, > EdgeRenderingFunction -> ({Black, Line[#1]} &), > VertexRenderingFunction -> ({EdgeForm[{Thickness[0.005], Red}], > Yellow, Disk[#1, 0.04]} &)] On the other hand, if I remove he VertexRenderingFunction option, I do >see vertex labels on the default (yellow boxes) vertex shapes: > >Any explicit setting for VertexRenderingFunction overrides the setting >>for VertexLabeling. >>Similarly for EdgeLabeling. >>If you want labels when using VertexRenderingFunction, you need to put >>them in explicitly in the VertexRenderingFunction rhs. The first example >>in the VertexRenderingFunction function page does this. >>If you want to recreate the default labeling inside >>VertexRenderingFunction, the following may help: >>VertexRenderingFunction -> (Text[ >> Framed[#2, {Background -> RGBColor[1, 1, .8], FrameStyle ->RGBColor[.94, .85, .36], FrameMargins -> Automatic}], #] &)] >>Carl Woll >>Wolfram Research >> > GraphPlot[{v1 -> v2, a}, {v2 -> v3, b}, {v3 -> v1, c}}, > Method -> Automatic, VertexLabeling -> True, > EdgeLabeling -> True, EdgeRenderingFunction -> ({Black, Line[#1]} &)] GraphPlot[Cycle[3], Method -> Automatic, VertexLabeling -> True, > EdgeLabeling -> True, EdgeRenderingFunction -> ({Black, Line[#1]} &)] Of course this now defeats the purpose of using GraphPlot so as to get >exactly the kind of vertex shapes that VertexRenderingFunction, above, >provides. Similarly with EdgeRenderingFunction. The kernel function GraphPlot doesn't seem to mesh very well with >Combinatorica's graph functions. This all still seems only half-baked. > >Take a look at GraphPlot, the graph rendering function that is built >>into the Mathematica kernel. I switched from using ShowGraph to >>GraphPlot after realising that it was (a) faster and (b) easier to >>customise. Here's what you want: >>GraphPlot[ >>Cycle[3], >>Method -> None, >>EdgeRenderingFunction -> ({Black, Line[#1]} &), >>VertexRenderingFunction -> ({EdgeForm[{Thickness[0.005], Red}], Yellow, >> Disk[#1, 0.04]} &) >>] >>You need to specify Method->None, otherwise GraphPlot will override the >>specified positions of the vertices in the graph and use its own default >>vertex positioning algorithm. >>VertexRenderingFunction is what you need to define in order to customise >>the appearance of the vertices. >>I provided a definition of EdgeRenderingFunction just so that the edges >>are rendered in the same way as ShowGraph. >>Jason >>-- >>J. McKenzie Alexander >>Department of Philosophy, Logic and Scientific Method >>London School of Economics and Political Science >>Houghton Street, London WC2A 2AE >> >> >With Mathematica 6, I can change the default style (medium black disk) >for rendering the vertices of a Combinatorica Graph like this: Needs[Combinatorica`] g = Cycle[3]; > ShowGraph[g, VertexStyle -> Disk[Large], VertexColor -> Red] But how can I, for example, change the vertex style so it is, say, a >large yellow disk with a thick red boundary? Or even just change it to >be a circle? I tried obvious things like the following, but they >cause errors: ShowGraph[g, VertexStyle -> Graphics[Circle[], ImageSize -> 20]] -- >Murray Eisenberg murray@math.umass.edu >Mathematics & Statistics Dept. >Lederle Graduate Research Tower phone 413 549-1020 (H) >University of Massachusetts 413 545-2859 (W) >710 North Pleasant Street fax 413 545-1801 >Amherst, MA 01003-9305 >Please access the attached hyperlink for an important electronic >>communications disclaimer: >>http://www.lse.ac.uk/collections/secretariat/legal/disclaimer.htm >> >> > > > === Subject: Re: changing style of vertices But how do I get GraphPlot to use labels that _I_ specify, rather than numbers -- when using a graph created with Combinatorica and without having to directly specify the labels as part of the graph structure. For example: g=Cycle[6]; GraphPlot[g, VertexLabeling->True,VertexRenderingFunction->(Text[...]&)] This sort of thing doesn't produce any vertex labels even if I first use something like: g = SetGraphOptions[g, VertexLabel -> Characters[b,a,f,e,d,c]]; (Comment: The documentation about graph display is really atrociously inadequate!) > Yes, GraphPlot seems to permit making nice vertices (or edges), but then >> the labeling -- either with a Graph object from Combinatorica or just >> the kind of graph described by the GraphPlot reference page -- does not >> seem to admit vertex labels or edge labels, at least so far as I can >> see. For example, neither of the following displays either vertex >> labels or edge labels: >> GraphPlot[Cycle[3], Method -> Automatic, VertexLabeling -> True, >> EdgeLabeling -> True, EdgeRenderingFunction -> ({Black, Line[#1]} &), >> VertexRenderingFunction -> ({EdgeForm[{Thickness[0.005], Red}], >> Yellow, Disk[#1, 0.04]} &)] >> GraphPlot[{{v1 -> v2, a}, {v2 -> v3, b}, {v3 -> v1, c}}, >> Method -> Automatic, VertexLabeling -> True, EdgeLabeling -> True, >> EdgeRenderingFunction -> ({Black, Line[#1]} &), >> VertexRenderingFunction -> ({EdgeForm[{Thickness[0.005], Red}], >> Yellow, Disk[#1, 0.04]} &)] >> On the other hand, if I remove he VertexRenderingFunction option, I do >> see vertex labels on the default (yellow boxes) vertex shapes: >> Any explicit setting for VertexRenderingFunction overrides the setting > for VertexLabeling. Similarly for EdgeLabeling. If you want labels when using VertexRenderingFunction, you need to put > them in explicitly in the VertexRenderingFunction rhs. The first example > in the VertexRenderingFunction function page does this. If you want to recreate the default labeling inside > VertexRenderingFunction, the following may help: VertexRenderingFunction -> (Text[ > Framed[#2, {Background -> RGBColor[1, 1, .8], FrameStyle -RGBColor[.94, .85, .36], FrameMargins -> Automatic}], #] &)] Carl Woll > Wolfram Research > GraphPlot[{v1 -> v2, a}, {v2 -> v3, b}, {v3 -> v1, c}}, >> Method -> Automatic, VertexLabeling -> True, >> EdgeLabeling -> True, EdgeRenderingFunction -> ({Black, Line[#1]} &)] >> GraphPlot[Cycle[3], Method -> Automatic, VertexLabeling -> True, >> EdgeLabeling -> True, EdgeRenderingFunction -> ({Black, Line[#1]} &)] >> Of course this now defeats the purpose of using GraphPlot so as to get >> exactly the kind of vertex shapes that VertexRenderingFunction, above, >> provides. >> Similarly with EdgeRenderingFunction. >> The kernel function GraphPlot doesn't seem to mesh very well with >> Combinatorica's graph functions. This all still seems only half-baked. >Take a look at GraphPlot, the graph rendering function that is built > into the Mathematica kernel. I switched from using ShowGraph to > GraphPlot after realising that it was (a) faster and (b) easier to > customise. Here's what you want: GraphPlot[ > Cycle[3], > Method -> None, > EdgeRenderingFunction -> ({Black, Line[#1]} &), > VertexRenderingFunction -> ({EdgeForm[{Thickness[0.005], Red}], Yellow, > Disk[#1, 0.04]} &) > ] You need to specify Method->None, otherwise GraphPlot will override the > specified positions of the vertices in the graph and use its own default > vertex positioning algorithm. VertexRenderingFunction is what you need to define in order to customise > the appearance of the vertices. I provided a definition of EdgeRenderingFunction just so that the edges > are rendered in the same way as ShowGraph. > Jason -- > J. McKenzie Alexander > Department of Philosophy, Logic and Scientific Method > London School of Economics and Political Science > Houghton Street, London WC2A 2AE > With Mathematica 6, I can change the default style (medium black disk) >> for rendering the vertices of a Combinatorica Graph like this: >> Needs[Combinatorica`] >> g = Cycle[3]; >> ShowGraph[g, VertexStyle -> Disk[Large], VertexColor -> Red] >> But how can I, for example, change the vertex style so it is, say, a >> large yellow disk with a thick red boundary? Or even just change it to >> be a circle? I tried obvious things like the following, but they >> cause errors: >> ShowGraph[g, VertexStyle -> Graphics[Circle[], ImageSize -> 20]] >> -- >> Murray Eisenberg murray@math.umass.edu >> Mathematics & Statistics Dept. >> Lederle Graduate Research Tower phone 413 549-1020 (H) >> University of Massachusetts 413 545-2859 (W) >> 710 North Pleasant Street fax 413 545-1801 >> Amherst, MA 01003-9305 >> > > Please access the attached hyperlink for an important electronic > communications disclaimer: > http://www.lse.ac.uk/collections/secretariat/legal/disclaimer.htm > -- Murray Eisenberg murray@math.umass.edu Mathematics & Statistics Dept. Lederle Graduate Research Tower phone 413 549-1020 (H) University of Massachusetts 413 545-2859 (W) 710 North Pleasant Street fax 413 545-1801 Amherst, MA 01003-9305 === Subject: Global setting of Graphics options for plot, listplot, listlogplot... Has anyone any experience (v6) with setting global graphics options. What I want to do is fairly simple. I want all my graphics to have a frame, automatic gridlines of a particular colour and the same font etc. Fonts are easy, I can set those as in Option Inspector (Formatting Options/Expression Formatting/Graphics Box Options/GraphicsBoxOptions) in BaseStyle and DefaultBaseStyle. Setting Frame and GridLinesStyles here is not a good plan though as plot legends and graphics Grid use invisible graphics boxes to position things. Adding frames and grids lines to all graphics boxes will corrupt these place holder boxes. I can, in my init.m file introduce altered values for Options[Plot] with Frame->True etc but I have to do this for Plot, ListPlot, LogPlot, ListLogPlot etc of which there are quite a few. Question is can anyone think of a better way? ZSG === Subject: Re: Number of monomials Works properly on my system. $Version 6.0 for Mac OS X x86 (64-bit) (March 13, 2008) Length[f[1] + f[2] + f[3]] 3 Length[f[1] + f[2]] 2 Length[f[1]] 1 Bob Hanlon > In[1]:=Length[f[1]+f[2]+f[3]] > Out[1]:=3 > OK! > In[2]:=Length[f[1]+f[2]] > Out[2]:=2 > OK! > In[3]:=Length[f[1]] > Out[3]:=0 > ??????????? > Who understand let share with me, please! Artur > === Subject: Re: Number of monominals According to the documentation, the function Length[expr] gives the number of elements in expr. Also The length of a symbol is 0. You have to write it as a list, if you want the expression to be counted. Length[{f[1]}] The other inputs are working, because Length counts the elements of the function Plus: In[1]:=Length[Plus[f[1],f[2],f[3]]] Out[1]:=3 OK! In[2]:=Length[Plus[f[1],f[2]]] Out[2]:=2 In[3]:=Length[f[1]] Out[3]:=0 I hope, that I could answer your question. Patrick === Subject: Re: Wrapping text to fit a rectangle Hi all, Depending on the stylesheet you use an interesting artifact can be realized when trying to frame text which is illustrated below. cc = Framed@(StringJoin @@ Table[The quick brown fox jumped over the lazy dog. , {10}]); Graphics[{Inset[cc, {0, 0}, {0, 0}, {400, 100}]}] Graphics[{Inset[cc, {0, 0}, {0, 0}, {400, 150}]}] The vertical line braces above appear because the top and bottom lines of the frame are hidden in the first example. One sometimes sees this typesetting effect starting a new chapter with a quotation in this format in books. Is there a Mathematica function designed to create this vertical line brace output with more controllability? I have searched the documentation and there appear to be possibilities with GraphicsGrid or Grid with its option Dividers but that still does not appear to be intended for achieving what I have in mind. It would be nice to have options similar to those for inserting horizontal line breaks. In addition it would be nice to be able to have full control of text size, wrap, justification, margin from text to vertical brace, vertical brace thickness and length, etc. Any guidance or suggestions would be appreciated. Syd Syd Geraghty B.Sc, M.Sc. sydgeraghty@mac.com My System Mathematica 6.0.1 for Mac OS X x86 (64 - bit) (June 19, 2007) MacOS X V 10.5 .20 it is not Text[] and not Rectangle[] but cc = Framed@(StringJoin @@ > Table[The quick brown fox jump over the lazy dog. , {10}]); Graphics[ > {Inset[cc, {0, 0}, {0, 0}, {400, 100}]} > ] may do what you want. >> Is there a way of wrapping Text[] so that it fits >> inside a Rectangle{]?? >> Robert Prince-Wright >> Houston >> TX, 77006 >> USA > === Subject: Re: The FinancialData Function I agree that FD has fantastic potential and maintaining and developing of it and similar functionality is a far more promising aim than, for example, trying to make Mathematica notebooks a standard for academic publishing. Recently I showed this to students in a financial mathematics class and everyone looked genuinly stunned. I can't believe WRI doesn't realize what a great idea they have stumbled on. Andrzej Kozlowski > I called Wolfram and asked the same question. I gather the FinancialData[] information is taken from data > packlets on a Yahoo server, and other sources. This funtion has the > potential to be VERY usefull to small enterprises and individuals > like me who don't have access to realtime equities data. Now, I've > tried to use FD to monitor the performance of my stock portfolio and > ran into problems with some of the international (Canada, Australia > etc.) stocks. While this was frustrating I was able to get > information on all my US and most of my internationals. I presume you have looked at the Help Documentation and at the > Wolfram Site - it gives enough to make a good start, but there seems > to be a mismatch between the functionality of FinancialData[] and > information available at the servers. This means you can make calls > and get nothing back. In that regard the documentation could be > improved. Now one caveat. I am not so sure - having spoken to WRI - that they > realise there should be some obligation on their part to maintain > FinancialData as a core function in Mathematica. Their tech suppport > gave me the impression that FD is being trialed and that its > continuance was to some degree dependent on their having free (or > cheap) access to the data servers. This scared me a little since I > have already spent significant amounts of time writing my portfolio > tracker and I can imagine there are small enterprises out there who > are doing the same. It seems like WRI could leave us stranded if > they don't continue to provide this function in Mathematica. BTW - the inclusion of Curated Knowledge like FD into Mathematica > 6. is pretty stunning. I am sure McKinsey and Co would have charged > me a few hundred thousand dollars to write my portfolio tracker - > instead I spend a few evening a week for a month and bingo I am > getting the same information tha Charles Schab gives me plus the > ability to analyze - well done WRI ! I would be intereseted to hear from others. > Can anyone tell me where I can get more information about the data > sources for Mathematica's new function FinancialData? > Gregory > Robert Prince-Wright > Houston > TX, 77006 > USA > --------------------------------- > Looking for last minute shopping deals? Find them fast with Yahoo! > Search. > Robert Prince-Wright > Houston > TX, 77006 > USA === Subject: Re: The FinancialData Function I called Wolfram and asked the same question. I gather the FinancialData[] information is taken from data packlets on a Yahoo server, and other sources. This funtion has the potential to be VERY usefull to small enterprises and individuals like me who don't have access to realtime equities data. Now, I've tried to use FD to monitor the performance of my stock portfolio and ran into problems with some of the international (Canada, Australia etc.) stocks. While this was frustrating I was able to get information on all my US and most of my internationals. I presume you have looked at the Help Documentation and at the Wolfram Site - it gives enough to make a good start, but there seems to be a mismatch between the functionality of FinancialData[] and information available at the servers. This means you can make calls and get nothing back. In that regard the documentation could be improved. Now one caveat. I am not so sure - having spoken to WRI - that they realise there should be some obligation on their part to maintain FinancialData as a core function in Mathematica. Their tech suppport gave me the impression that FD is being trialed and that its continuance was to some degree dependent on their having free (or cheap) access to the data servers. This scared me a little since I have already spent significant amounts of time writing my portfolio tracker and I can imagine there are small enterprises out there who are doing the same. It seems like WRI could leave us stranded if they don't continue to provide this function in Mathematica. BTW - the inclusion of Curated Knowledge like FD into Mathematica 6. is pretty stunning. I am sure McKinsey and Co would have charged me a few hundred thousand dollars to write my portfolio tracker - instead I spend a few evening a week for a month and bingo I am getting the same information tha Charles Schab gives me plus the ability to analyze - well done WRI ! I would be intereseted to hear from others. Can anyone tell me where I can get more information about the data sources for Mathematica's new function FinancialData? Gregory Robert Prince-Wright Houston TX, 77006 USA --------------------------------- Looking for last minute shopping deals? Find them fast with Yahoo! Search. Robert Prince-Wright Houston TX, 77006 USA === Subject: conversion of sin to cos Hello all, Here is my problem. I have a very long product of cosines with arguments of the form k*Pi, k being integers. I want to convert this expression to a sum of cosines. TrigReduce works fine, except that it converts cos to sin. So, I want all the sin (after the TrigReduce) to be converted to cos and the arguments be of the form p*Pi, p being rational of course. It has something to do with Hold or HoldAll, but I don't know the details. Or perhaps the TrigReduce can be overridden somehow. Can someone help? === Subject: Re: Mixed Numerical Derivatives I have version 6 and can not find ND. Nevertheless, you could try an iterative approach. E.g.: ND[ ND[fun[x,y],{x,2},1] ,{y,2}, 1] hope this helps, Daniel > How can I come up with the Hessian of a function, at a particular > point, which can only be evaluated numerically? If I had a symbolic > function, I could do something like In[123]:= > D[x^3 + z*y^-1 + z^(1/2), {{x, y, z}, 2}] /. {x -> 3, y -> 5, > z -> 12} Out[123]= {{18, 0, 0}, {0, 24/ > 125, -1/25}, {0, -1/25, -1/(96 Sqrt[3])}} The function I'm interested in, though, can only be calculated > numerically. Using ND, I can find the diagonal elements of the > Hessian: In[92]:= rules = Last[ > FindMaximum[{Total[logPr[vdt, ddt, var, #] & /@ testData], ddt > 0, > var > 0}, {{vdt, .9}, {ddt, 120}, {var, 90}}]] Out[92]= {vdt -> 0.95945, ddt -> 151.097, var -> 103.255} In[111]:= Needs[NumericalCalculus`] In[124]:= ND[ > Total[logPr[vdtp, ddt, var, #] & /@ testData] /. rules, {vdtp, 2}, > Evaluate[vdt /. rules]] Out[124]= -64.4011 But what about the off diagonal elements? > === Subject: Re: setting elements of an array based on a condition Hi Claus, to set elements <0 to 0 you may use: W/. x_/;x<0 -> 0 Adding all elements in a column is easier done if you Transpose W first so that you add all elements in a row. This can be done by: Total /@ W hope this helps, Daniel > I have one array, W, which for testing purposes has 25 rows and 50 columns. > There are two more things I want to accomplish with this: > 1) I want to set all elements of W which are smaller than zero to zero. > 2) Then I want to calculate the sum of the elements in each column of W. > How can I do this? The code below shows how I get to W. Claus X = RandomReal[{0, 1}, 50]; > Y = RandomReal[{0, 1}, 50]; BinWidth = 0.2; > Radius = 0.2; xyzVals2 = Table[ > {i/(1/BinWidth) + (BinWidth/2) > , j/(1/BinWidth) + (BinWidth/2) > } > , {i, 0, (1/BinWidth) - 1} > , {j, 0, (1/BinWidth) - 1}]; RasterPtsVals = Partition[Flatten[xyzVals2], 2] RasterX = RasterPtsVals[[All, 1]] > RasterY = RasterPtsVals[[All, 2]] XDiffSq = (RasterX - a /. a -> X)^2; > YDiffSq = (RasterY - b /. b -> Y)^2; > Dist = Sqrt[(XDiffSq + YDiffSq)]; W = 1 - (Dist/Radius) > === Subject: Re: setting elements of an array based on a condition > I have one array, W, which for testing purposes has 25 rows and 50 columns. > There are two more things I want to accomplish with this: > 1) I want to set all elements of W which are smaller than zero to zero. Clip[W, {0, Infinity}] > 2) Then I want to calculate the sum of the elements in each column of W. > How can I do this? Plus @@@ W or Total /@ W === Subject: Re: How to put text on a curved surface? > I would like to put Mathematica on a curved surface, e.g. a torus. > Can anyone help here? > with friendly greetings, I haven't tried it but there is an example on this page: http://users.dimi.uniud.it/~gianluca.gorni/Mma/Mma.html === Subject: Re: Defining a Play[] function for Drawbar Organ Emulation > Although I have no problem PLOTing such a function as this, I cannot > get it to work with the Play[] function. Can anyone help? This is > based on the 11-drawbar organ stops used on some hammond organs (such > as the X-66 model) which I am trying to emulate for additive synthesis > output in a future Demonstration Project (I am using Mathematica 6). ElevenDrawbars[f_, d_String] := > Module[{d1, d2, d3, d4, d5, d6, d7, d8, d9, d10, h10, d11, h11, z}, > d = StringTake[d, {1}] <> StringTake[d, {2}] <> StringTake[d, {4}] object 00 8845 041 00. >> What Mathematica is telling you is that one cannot change the value of a string, AA = BB is illegal (as well as meaningless). The string parameter d, therefore, cannot be modified by the first *Set* statement of your code: use another name for it, like dd in the following example. ElevenDrawbars[f_, d_String] := Module[{dd, d1, d2, d3, d4, d5, d6, d7, d8, d9, d10, h10, d11, h11, z}, dd = StringTake[d, {1}] <> StringTake[d, {2}] <> StringTake[d, {4}] <> StringTake[d, {5}] <> StringTake[d, {6}] <> StringTake[d, {7}] <> StringTake[d, {9}] <> StringTake[d, {10}] <> StringTake[d, {11}] <> StringTake[d, {13}] <> StringTake[d, {14}]; d1 = ToExpression[StringTake[dd, {1}]]; d2 = ToExpression[StringTake[dd, {2}]]; d3 = ToExpression[StringTake[dd, {3}]]; d4 = ToExpression[StringTake[dd, {4}]]; d5 = ToExpression[StringTake[dd, {5}]]; d6 = ToExpression[StringTake[dd, {6}]]; d7 = ToExpression[StringTake[dd, {7}]]; d8 = ToExpression[StringTake[dd, {8}]]; d9 = ToExpression[StringTake[dd, {9}]]; d10 = ToExpression[StringTake[dd, {10}]]; h10 = d11/2; d11 = ToExpression[StringTake[dd, {11}]]; h11 = d11/2; z = N[2 Pi]; Play[d1 Sin[1/2 f x z] + d2 Sin[3/2 f x z] + d3 Sin[f x z] + d4 Sin[2 f x z] + d5 Sin[3 f x z] + d6 Sin[4 f x z] + d7 Sin[5 f x z] + d8 Sin[6 f x z] + d9 Sin[8 f x z] + d10 Sin[7 f x z] + h10 Sin[9 f x z] + d11 Sin[10 f x z] + h11 Sin[12 f x z], {x, 0, z}, SampleDepth -> 16, SampleRate -> 44100]] ElevenDrawbars[440, 00 8845 041 00] [... sound player deleted ...] HTH, -- === Subject: Re: The FinancialData Function I believe that the curated data is a good step forward for WRI. Most of the FD data can be accessible elsewhere in some cases free. In the US, we are flipping the bill so the gov has made SEC data available and Sarbanes-Oxley has made filings more transparent. As for getting Stock market trading information free I think at end of day it is free from the exchanges but realtime feed is well controlled so entities can make their money from selling and reselling the data. I looked into FD for a project but I was getting the data elsewhere so found no reason to use an experimental service. There were other issues such as company normalization. On the WRI website they request feedback as to what kind of data we would like to see in FD (http://support.wolfram.com:80/mathematica/paclets/financialdataqanda.en.htm l). In this and other thread of late there is mention of how to get Mathematica to be a publishing standard. Well I think that more Curated data would a great help. Richard Feynman stated that having a bag of tricks is a great way to impress new users to your field of interest. Curated data in Mathematica can help establish some standard bag of tricks. For example, I suggested that WRI curate Observed Tidal data. Political or not it would be great to get all tidal data and actually show from data sea level trends. Having curated data would allow in forming hypothesis, as the data would serve as observation by proxy. If user want permance of data as a result of doing mission critical work, then I don't think curated data would fit. It would be like using the Astronomical data to calculate rocket launches. Possibly can be done but is it the valid thing to do. Mathematica could have more curated data. Tides (http://tidesandcurrents.noaa.gov/tsunami/, links to Eathquake, some station also monitor Meterological data Sloane's Integer Sequence For example, I find http://www.research.att.com/~njas/sequences/A100000 a great pivot point to get people interested in Math or just to ponder. [Already are cross references between MathWorld and Sloane's (But a quick builtin function that parses or generates Sloane's sequence would add to a bag of tricks.)] Census data http://factfinder.census.gov/home/saff/main.html?_lang=en or http://dataferrett.census.gov/ Etc.. Data does not have to be managed by WRI alone as it could be on loan or data that is parked with WRI. (It would be nicer if there were more data web services.) A curated science and math bibliography. To reduce the cost of entry to using Mathematica, find a way to have access to a remote Kernel Farm that works as an ASP. Running and Evaluating Tutorial Free. Ad hoc calculation would depend on how fast you want the data back (priority) from a Kernel Farm (A way to tax GridMathematica). How to compete with SAS at Student license fees of ~$30? I think WRI and Mathematica should set some focus on the life and medical sciences. Mathematica can Export and Import DICOM but pays little attention to HL7, X12, CCR, CDA. For clinical research being able to Import these formats can cut out the need for a data repository, researchers just get the raw data. HealthCare IT is growing for many reasons but one of the growing needs is for analysis and reporting of collected data. Mathematica does this well. (SAS is entrenched here, epidemiology, bioinformatics, may be there are more mathematica users in these fields than my guess.) WRI is doing fine just that more items need to be integrated and connected. I read recently that the show Numbers draws about 11 million viewers and that some viewers say that the mathematical explainations makes them feel smarter. I think that Mathematica needs this quick bag of tricks. The demonstration site is a good start but IMO not all GUIs need a slider or button, these new GUIs need more controls. I think there is a need to ease new users to Mathematica some will be more casual users, but have a bag of tricks to show to other potential users; some will be dedicated users and they will have their bag of tricks too. Just as something as a soap film or soap bubbles can attract curious kids to top notch physicists. The tricks brings them in but it is because there is something both fun and serious. Hans >I share your concerns, but hold more hope that Wolfram realise that >charging ~$2500 for a license and $500 for Premier Service results in some >obligations to their customers. That said, I was disappointed that their Tech Support didn't follow up on > the concerns I expressed about 6mths ago - is their statement that > FinancialData is 'experimental' a caveat intended to warn us all that it's > not to be used for serious work? I hope not. We are all now pretty used to > the fact that Mathematica is well written, and that QA/QC is exceptionally > good (despite those who think they or others can do better). Given this, I > am sure they have fully understood just how powerful the curated data > facilities can be for the user. Renegging in the FD function would not be > acceptable to me and I suspect many others. Now, you mention the data paclets could be at risk and that Yahoo could > suddenly start charging WRI (if they are not already). The solution would > be simple, however, since I know there are many financal data providers > out there who could fill the gap - at a cost. I would like to hear from WRI about this since its a key issue. I've never heard of this function, but have one immediate strong > reaction/question: Is there -- or will there soon be -- a fully open, officially > standardized, fully and openly specified, widely and near universally > accepted, stable, long-term, NON-proprietary set of **formats** > for the data and information that is to be transmitted back > and forth between data providers and data users in this > system? [Something akin to the more or less open, universal and stable graphics > standards that have emerged over time.] Lacking that, I wouldn't personally go near this kind of financial data > distribution system and related tools like FinancialData for building > anything that was of any real and continuing importance to me. Think of mapping data, GPS and topographic data, or satellite imagery > and related software tools as an analogous system. I play with some of > this data, plan journeys using MapQuest, hiking trips using Google Earth > (an incredible tool), etc -- but if someone suddenly decided to change > all the standards for this data, I could still use all my old stored > data and tools -- or just do without. (There would of course be many > important commercial enterprises that would be much more seriously > impacted.) But then suppose people get important, continuing personal or business > activities deeply involved in an information system that uses tools like > FinancialData; the data providers and Wolfram somehow get cross-wise > commercially; and the data providers threaten to change their formats > just enough to screw Wolfram (and all FinancialData users). Or, suppose the data providers decide to throw digital rights management > complexities all over their data, as is the case now with music, films, > video -- and the deep pockets financial data providers manage to bribe > Congress to require that all computer tools like FinancialData contain > provisions to enforce these DRM complexities. This may all come across as paranoid fears, and maybe it is -- but look > what has actually happened in other areas of widely distributed > electronic information distribution . . . > Robert Prince-Wright > Houston > TX, 77006 > USA >