Tools for Mathematical Calculations

Click here to load reader

Transcript of Tools for Mathematical Calculations

Tools For Mathematical Calculations Graduate Student Colloquium Talk February 20, 2008 Fritz Keinert This talk gives an overview of some programs that can take the tedium out of mathematical calculations. They perform calculations such as differentiation, integration, solving nonlinear equations, ODEs and PDEs, Taylor series expansions, plotting functions, and so on. We will concentrate on four programs that are available at ISU: Mathematica, Maple, Matlab, SciLab. If you are looking at this on the web: the images are very large because this is intended to be projected in front of an audience. I can crank up the size of text, but the pictures stay fixed.

Herramientas para clculos matemticos Graduate Student Coloquio Talk 20 de febrero 2008 Fritz Keinert Esta charla presenta un resumen de algunos programas que pueden tomar el tedio de clculos matemticos.Realizan clculos como la diferenciacin, integracin, resolucin de ecuaciones no lineales, odas y PDE desarrollos en serie de Taylor, funciones de trazado, y as sucesivamente. Nos concentraremos en cuatro programas que estn disponibles en ISU: Mathematica, Maple, Matlab, SciLab. Si usted est buscando en esto en la web: las imgenes son muy grandes ya que este est destinado a ser proyectado en frente de una audiencia. Puedo subir el tamao del texto, pero las imgenes quedarse fijo.

The Programs, And Where To Find Them Mathematica Mathematica is designed to provide symbolic answers, that is, to solve problems in closed form. It can also solve these problems numerically, to arbitrary precision, but gives no detail on how that is done internally. It is not well suited for extensive numerical computations. We have 10 copies running on public machines in the Math Department, all of them recent versions with good support. This is one good option if you need a symbolic calculator.

Los programas y dnde encontrarlos Mathematica Mathematica est diseado para proporcionar respuestas simblicas, es decir, para resolver los problemas en forma cerrada. Tambin puede resolver estos problemas de forma numrica, a la precisin arbitraria, pero no da detalles sobre la forma en que se realiza internamente. No es muy adecuado para extensos clculos numricos.Tenemos 10 copias que se ejecutan en mquinas pblicas en el Departamento de Matemticas, todos ellos versiones recientes con un buen apoyo. Esta es una buena opcin si usted necesita una calculadora simblica.

Mathematica is expensive. A couple of years ago it was $800 per license. The department pays for five public copies in Carver 449. I discovered another five copies in Carver 400, so there are 10 public copies around, with version numbers between 5.0 and 6.0. The latest version is 6.0. I used version 5.2 installed in the lab to generate the examples below. Windows XP machines: In Carver 449, machines 1 through 5 (front row left, if you are standing by the whiteboard), version 5.2. In Carver 400, machines C00179 (version 5.1) and C00180 (version 5.2), and the scanner machine (version 6.0). The C00179 etc. refers to the inventory number listed on a big sticker attached to the computer. You can access Mathematica by looking for it under Start -> Programs. The machines in 449 also have a link on the desktop. Linux machines: In Carver 400, pollux (version 5.2) and proton (version 5.0). The executables are in/usr/local/Wolfram/Mathematica/5.x/Executables/math/. In addition, there is a copy of Mathematica 2.2.3 in /afs/iastate.edu/public/mathematica/. I am not sure which kind of machine it runs on, but it is ancient anyway. The publisher's web site is http://www.wolfram.com/. Maple Maple is also a symbolic calculator. It has similar capabilities to Mathematica, and a similar price tag. In early 2007, their web site quoted me a price of $997 for a single user copy, with academic discount. The current version is 11. The examples below are from version 10.

Mathematica es caro. Hace un par de aos que era de $ 800 por licencia. El departamento paga cinco copias pblicas de Carver 449. Descubr otros cinco ejemplares en Carver 400, por lo que hay 10 copias pblicas de todo, con nmeros de versin entre 5.0 y 6.0. La ltima versin es la 6.0. He utilizado la versin 5.2 instalada en el laboratorio para generar los ejemplos a continuacin.Mquinas de Windows XP: En Carver 449, mquinas 1 travs 5 (primera fila a la izquierda, si usted est de pie por la pizarra), versin 5.2. En Carver 400, mquinas C00179 (versin 5.1) y C00180 (versin 5.2), y la mquina de escner (versin 6.0). El C00179 etc refiere al nmero de inventario que aparece en una gran etiqueta pegada al ordenador. Se puede acceder a Mathematica por buscarlo en Inicio -> Programas. Las mquinas de 449 tambin tienen un enlace en el escritorio.Mquinas Linux: En Carver 400, Pollux (versin 5.2) y protones (versin 5.0). Los ejecutables estn en / usr/local/Wolfram/Mathematica/5.x/Executables/math /.Adems, hay una copia de Mathematica 2.2.3 en / afs / iastate.edu / public / mathematica /. No estoy seguro de qu tipo de mquina que se ejecuta en, pero es antigua de todas formas. El sitio web de la editorial es http://www.wolfram.com/ . MAPLE Maple es tambin una calculadora simblica. Cuenta con capacidades similares a Mathematica, y un precio similar. A principios de 2007, su sitio web me pidieron un precio de 997 dlares de una copia de usuario, con descuento acadmico. La versin actual es 11. Los ejemplos a continuacin son de la versin 10. ISU tiene una licencia de sitio para los estudiantes. Los detalles se pueden encontrar enhttp://www.it.iastate.edu/sldb/view.php?id=18 . Las instrucciones que siguen siendo de la versin de Maple 10.Versin 11 sali a mediados de 2007. No est claro si el software con licencia de sitio es la versin 10 u 11. Una antigua versin 6 de arce es disponible en /

ISU has a site license for students. Details can be found at http://www.it.iastate.edu/sldb/view.php?id=18. The instructions there are still for Maple version 10. Version 11 came out in mid-2007. It is not clear whether the site-licensed software is version 10 or 11. An ancient Version 6 of Maple is available at /afs/iastate.edu/public/maplevr6/ for Dec Alphas and for Linux PCs. Public machines of this type in Carver 400 are mercury and duluth (Alphas), and proton and pollux (Linux). I would recommend the Linux machines, they seem to be much faster than the antique Alphas. The executables are calledmaple (text interface) or xmaple (X windows interface). The help files are missing, so you are on your own. The publisher's web site is http://www.mapletech.com/. Matlab Matlab is designed primarily to provide numerical answers. It can perform some symbolic computations by internally calling Maple, but its symbolic capabilities are limited compared to the Mathematica and Maple. The numerical algorithms used are described in detail in the documentation, and for many tasks there is a choice of different algorithms. Matlab is available on all machines in the Math department. It is used extensively in numerical analysis and other applied math courses. We have a site license that lets faculty install Matlab on their machines, even at home. There is a separate site license for students. Details are given athttp://www.it.iastate.edu/sldb/view.php?id=21. The examples below were done in version 7.0.4, which is also the version installed in the labs.

afs/iastate.edu/public/maplevr6 / diciembre de Alphas y PCs Linux. Mquinas pblicos de este tipo en Carver 400 son el mercurio y Duluth (Alphas) y protones y Plux (Linux).Yo recomendara las mquinas Linux, parecen ser mucho ms rpido que los Alfas antiguos. Los ejecutables se llaman maple (interfaz de texto) o xmaple (X interfaz de ventanas). Los archivos de ayuda se estn perdiendo, por lo que est por su cuenta. El sitio web de la editorial es http://www.mapletech.com/ . Matlab Matlab est diseado principalmente para proporcionar respuestas numricas. Se pueden realizar algunos clculos simblicos llamando internamente Arce, pero sus capacidades simblicas son limitados en comparacin con el Mathematica y Maple. Los algoritmos numricos utilizados se describen en detalle en la documentacin, y para muchas tareas hay una seleccin de diferentes algoritmos. Matlab est disponible en todos los equipos en el departamento de matemticas. Es ampliamente utilizado en el anlisis numrico y otros cursos de matemticas aplicadas. Tenemos una licencia de sitio que permite a los profesores Matlab instalar en sus mquinas, incluso en casa. Hay una licencia independiente para los estudiantes. Los detalles aparecen enhttp://www.it.iastate.edu/sldb/view.php?id=21 . Los ejemplos siguientes se realizaron en la versin 7.0.4, que es tambin la versin instalada en los laboratorios. El sitio web de la editorial es http://www.mathworks.com/ . Observaciones secundarios: Acabo de descubrir la semana pasada que algunas laboratorio de computacin est ejecutando un versioin llamado R2006. Esto eleva el nmero de versin diferente de sellos de calidad hasta tres.Mi propia verson 7.0.4 tambin se conoce como liberacin 12 y el R2006 es, probablemente, tambin llamado R13 o R14. No s por qu es tan difcil de seguir con un nico esquema.

Scilab Scilab es la respuesta de la comunidad de cdigo abierto a Matlab. Originalmente desarrollado por INRIA (Institut National du Recherche en Informatique et Automatique) y la ENPC (cole Nacional de Puentes y Caminos),ahora es supervisado por un consorcio de 23 miembros. El programa, con cdigo fuente est disponible gratuitamente. La ltima versin es la 4.1.2. Est destinado a tener la misma funcionalidad que Matlab. ISU es alentador departamentos para cambiar a software libre (Microsoft Office a Open Office, por ejemplo), y se propone Scilab como sustituto de Matlab. La sintaxis bsica de Scilab es muy similar a Matlab. Por ejemplo, si A y B -1 son matrices, entonces X = A / B significa X = AB (o, ms generalmente, X es la solucin de mnimos cuadrados para XB = A), mientras que X = A / B es la divisin elementwise. Las matrices se introducen como A = [1,2, 3,4]. La notacin de a: b: c significa "los nmeros de A a C en pasos de b", y as sucesivamente. Algunas secuencias de comandos de Matlab simples funcionarn sin cambios en Scilab. Sin embargo, los nombres y sintaxis de muchas rutinas incorporadas son diferentes, definicin de una subrutina es diferente, y algunas de las caractersticas de Matlab no puede proporcionar. Pocas rutinas de Matlab se ejecutarn sin cambios en Scilab. Scilab proporciona una herramienta para convertir las rutinas de MATLAB para Scilab. No he probado todava. Mi opinin: Scilab es mejor que Matlab en algunos aspectos. En particular, se hizo mucho ms fcil interfaz para subrutinas escrito en Fortran o C. Esto se puede hacer en Matlab, pero es una pesadilla de programacin. (Hablo por experiencia aqu). Todo el programa es de cdigo abierto, por lo que puede poner en prctica un montn de cosas si usted decide invertir el esfuerzo. Me gusta el hecho de que se puede establecer el nmero de decimales mostrados a cualquier cosa que usted elija, en Matlab, o bien obtener 5 decimales o 15, nada ms. Scilab es capaz de leer archivos de datos de Matlab y otros formatos de hojas de clculo (Excel, por ejemplo).

The publisher's web site is http://www.mathworks.com/. Side remarks: I just discovered last week that some lab computer are running a versioin called R2006. That brings the number of different version labeling schemes up to three. My own verson 7.0.4 is also known as release 12, and the R2006 is probably also called R13 or R14. I don't know why it is so hard to stick with a single scheme. Scilab Scilab is the open source community's answer to Matlab. Originally developed by INRIA (Institut National du Recherche en Informatique et Automatique) and ENPC (cole National des Ponts et Chausses), it is now overseen by a 23-member consortium. The program, complete with source code, is freely available. The latest version is 4.1.2. It is intended to have the same functionality as Matlab. ISU is encouraging departments to switch to free software (Microsoft Office to Open Office, for example), and they are proposing Scilab as a replacement for Matlab. The basic syntax of Scilab is very similar to Matlab. For example, if A and B -1 are matrices, then X = A/B means X = AB (or more generally, X is the least squares solution to XB = A), while X = A./B is elementwise division. Matrices are entered as A = [1,2;3,4]. The notation a:b:c means "the numbers from a to c in steps of b", and so on. Some simple Matlab scripts will run unchanged in Scilab. However, names and syntax of many built-in routines are different, subroutine definition is different, and some of Matlab's features may not be provided. Few Matlab routines will run without changes in Scilab. Scilab does provide a tool to convert Matlab routines to Scilab. I haven't tried that yet. My opinion: Scilab is better than Matlab in some respects. In particular, they

made it a lot easier to interface to subroutines written in Fortran or C. This can be done in Matlab, but it is a programming nightmare. (I speak from experience here). The whole program is open source, so you can implement lots of things if you choose to invest the effort. I like the fact that you can set the number of displayed decimals to anything you choose; in Matlab, you either get 5 decimals or 15, nothing else. Scilab is able to read Matlab data files and other formats (Excel spreadsheets, for example). However, Scilab also has shortcomings. For example, symbolic calculation is only offered for rational functions at this point. I also ran into inconsistent syntax and lack of explanation of the underlying algorithms (see integration example below). If you need to do a lot of interfacing with Fortran, C or anything nonstandard for your research, Scilab is worth a look. For teaching purposes I would stick with Matlab at this point. Scilab is not widely installed in the department, but if you want it, all you have to do is ask. Scilab can be downloaded from http://www.scilab.org/. Other Programs Macsyma is symbolic calculator with capabilities similar to Mathematica and Maple. We had it running in the department 15 years ago. At that time it was very clumsy to use, and obviously written by many people who didn't talk to each other: different portions of it had totally different syntax. I think they cleaned it up considerably since then, and it is probably a nice product now, but I am not aware of any copies of it on campus. There are other symbolic calculators I have heard of: Singular and Derive. I don't know anything about their capabilities. They may be more specialized. We used to have Gap, which is a group theory calculator. It may still be around.

Sin embargo, Scilab tambin tiene defectos. Por ejemplo, el clculo simblico slo se ofrece para funciones racionales en este punto. Tambin me encontr con la sintaxis incoherente y falta de explicacin de los algoritmos subyacentes (vase el ejemplo de la integracin de ms abajo). Si tiene que hacer un montn de interactuar con Fortran, C o algo no estndar para su investigacin, Scilab es digno de una mirada. Para fines didcticos que se quedara con Matlab en este punto. Scilab no es ampliamente instalada en el departamento, pero si usted lo quiere, todo lo que tienes que hacer es preguntar. Scilab se puede descargar desde http://www.scilab.org/ . Otros Programas Macsyma es calculadora simblica con capacidades similares a Mathematica y Maple. Habamos funcionando en el departamento hace 15 aos. En ese momento, era muy torpe para utilizar, y obviamente escrito por muchas personas que no hablan el uno al otro: diferentes partes de ella tenan totalmente diferente sintaxis. Creo que haban limpiado de forma considerable desde entonces, y es probablemente un buen producto ahora, pero no estoy al tanto de cualquier copia del mismo en el campus. Hay otras calculadoras simblicas que he odo hablar de: Singular y derive. No s nada acerca de sus capacidades. Pueden ser ms especializado. Solamos tener Gap, que es una calculadora de la teora de grupos.Todava puede ser alrededor. Octave es la versin del Proyecto GNU de Matlab: cdigo abierto y de libre acceso, la intencin de ser totalmente compatible con Matlab. Mir una vez, pero no en gran detalle. Mi impresin fue que es equivalente a una versin anterior de Matlab, antes de aadir los grficos de lujo, tipos de datos, etc

Octave is the GNU Project's version of Matlab: open source, freely available, intended to be fully compatible with Matlab. I looked at it once, but not in great detail. My impression was that it is equivalent to an earlier version of Matlab, before they added the fancy graphics, data types, etc.

Mathemat ica Uso principal clculo simblico La disponibili dad es moderada (10 copias pblicos). El apoyo es bueno (los ejemplare s que tenemos son recientes y vienen con manuales completos ) basado en texto o componer s texto, TeX, HTML,

MAPLE clculo simblico Disponibilidad para los estudiantes es bueno.Disponibi lidad para el profesorado es inexistente. El apoyo es bueno (extenso sistema de ayuda en lnea)

Matlab clculo numrico Disponible en todas partes, muy utilizado por los profesores y las clases. Buena Support (amplia ayuda en lnea, mucha gente con conocimie ntos de todo) basado en texto slo

Scilab clculo numrico Disponible en todas partes. El apoyo es dbil (la ayuda en lnea es bastante bsico).

Mathematic Maple a Main Use symbolic computation Availability is moderate (10 public copies). Support is good (the copies we have are recent and come with complete manuals) symbolic computatio n Availability for students is good. Availability for faculty is nonexisten t. Support is good (extensive online help system) text-based or typeset yes

Matlab numeric computation Available everywhere; widely used by faculty and in classes. Good Support (extensive online help, many knowledgeabl e people around) text-based only yes

Scilab numeric computatio n Available everywhere . Support is weak (the online help is quite basic). Formato de salida Guardar el trabajo en formato interno Guardar / imprimir una copia de su

Soporte y disponibilidad

Support and Availability

basado en texto o componer

basado en texto slo

s

s

s

Output formatting Save work in

text-based or typeset yes

text-based only yes

texto, TeX, HTML

Slo texto

Slo texto

internal format Save/print a transcript of your work text, TeX, HTML, MathML text, TeX, HTML text only text only TeX (rational functions only) Fortran (subroutine s only) Fortran, C, whatever else you feel like programmin g yourself Very extendable yes

trabajo

MathML TeX (slo funciones racionales ) Fortran (slo subrutinas ) Fortran, C, cualquier otra cosa que usted se siente como la programac in de ti mismo Muy ampliable s

Guardar frmulas como

TeX, TeX, Fortran, C, Fortran, C, Java, Matlab MathML

TeX, Fortran, C

Save formulas as

TeX, Fortran, C, MathML

TeX, Fortran, C, Java, Matlab

TeX, Fortran, C

Interface to ?? other programs

??

Fortran, C, Maple, Excel, lab instruments, ... Not easy but possible yes

Interfaz con otros programas

??

??

Fortran, C, Maple, Excel, instrument os de laboratorio, ... No es fcil, pero es posible s

Plotting capabilities Calculate values of special functions (Bess el functions, error function, hypergeometric functions, etc.)

yes

yes

Capacidades Trazado Calcular los valores de funciones especiales(funci ones de Bessel, la funcin de error, funciones hipergeomtrica, etc)

s

s

yes

yes

yes

yes

s

s

s

s

Problema 1: Integracin Integrar (x 1) / (x + x 1), tanto como una integral indefinida y como una integral definida de 0 a 1. Para la integral definida, tambin puede encontrar la respuesta en decimales con 30 dgitos. Mathematica2

En [2]: = Integrar [(x 1) / (x ^ 2 + x +1), x] Salida [2] = Problem 1: Integration Integrate (x+1)/(x +x+1), both as an indefinite integral and as a definite integral from 0 to 1. For the definite integral, also find the answer as a decimal with 30 digits. Mathematica Salida [3] = In[2]:= Integrate[(x+1)/(x^2+x+1),x] Out[2]= En [7]: = N [%, 30] Salida [7] =2

En [3]: = Integrar [(x 1) / (x ^ 2 + x 1), {x, 0,1}]

In[3]:= Integrate[(x+1)/(x^2+x+1),{x,0,1}] Arce

> Int ((x 1) / (x ^ 2 + x +1), x); Out[3]=

> Int ((x 1) / (x ^ 2 + x +1), x = 0 .. 1); In[7]:= N[%,30] Out[7]= > Evalf [30] (%); Maple Matlab Matlab es principalmente una calculadora numrica. Nosotros hacemos la integral numricamente primero, entonces la integral definida simblica. Tenga en cuenta que la precisin por defecto es bastante bajo. > int((x+1)/(x^2+x+1),x=0..1); >> Ayuda quad QUAD evaluar numricamente integrante, cuadratura de Simpson adaptativa. Q = QUAD (FUN, A, B) trata de aproximar la integral de la funcin FUN de A a B con una precisin de un error de 1.e-6 utilizando recursiva adaptativo Simpson cuadratura. La funcin Y = FUN (X) debe aceptar un argumento vector X y devolver un resultado vector Y, la integrando evaluado en cada elemento de X. ... Ver tambin quadv, quadl, dblquad, triplequad, @, trapz.

> int((x+1)/(x^2+x+1),x);

> evalf[30](%);

Matlab Matlab is primarily a numerical calculator. We do the definite integral numerically first, then the symbolic integral. Note that the default accuracy is fairly low.

>> help quad QUAD Numerically evaluate integral, adaptive Simpson quadrature. Q = QUAD(FUN,A,B) tries to approximate the integral of function FUN from A to B to within an error of 1.e-6 using recursive adaptive Simpson quadrature. The function Y = FUN(X) should accept a vector argument X and return a vector result Y, the integrand evaluated at each element of X. ... See also quadv, quadl, dblquad, triplequad, @, trapz. >> f = inline('(x+1)./(x.^2+x+1)') f= Inline function: f(x) = (x+1)./(x.^2+x+1) >> quad(f,0,1) ans = 0.85160606414482 >> quad(f,0,1,1.e-15) ans = 0.85160603837309 >> syms x >> int((x+1)/(x^2+x+1)) ans = 1/2*log(x^2+x+1)+1/3*3^(1/2)*atan(1/3*(2*x+1)*3^(1/2)) >> I = int((x+1)/(x^2+x+1),0,1)

>> F = inline ('(x 1). / (X ^ 2 + x 1)') f= Funcin en lnea: f (x) = (x 1). / (x ^ 2 + x 1) >> Quad (f, 0,1) ans = 0.85160606414482 >> Quad (f, 0,1,1. E-15) ans = 0.85160603837309 >> Syms x >> Int ((x 1) / (x ^ 2 + x +1)) ans = 1/2 * log (x ^ 2 + x 1) 1/3 * 3 ^ (1/2) * atan (1/3 * (2 * x 1) * 3 ^ (1/2)) >> I = int ((x 1) / (x ^ 2 + x 1), 0,1) ans = 1/2 * log (3) 1/18 * 3 ^ (1/2) * pi >> Doble (I) ans = 0.85160603837309 >> VPA (I, 30) ans = ,851606038373091154129968994735

Scilab Scilab ha extremadamente limitada herramientas simblicas. Yo no era capaz de encontrar una rutina de integracin simblica. Slo hice la integracin numrica.

ans = 1/2*log(3)+1/18*3^(1/2)*pi >> double(I) ans = 0.85160603837309 >> vpa(I,30) ans = .851606038373091154129968994735

Scilab Scilab has extremely limited symbolic tools. I wasn't able to find a symbolic integration routine. I only did the numerical integration.

-> Funcin y = f (x), y = (x 1) / (x ^ 2 + x 1), endfunction -> Format ('v', 30) -> [I, err] = intg (0,1, f) err = 0,0000000000000094547263 I= ,8516060383730911231837 -> Integrate ('(x 1) / (x ^ 2 + x 1)', 'x', 0,1) ans = ,8516060383730911231837 -> Ans - I ans = 0.

Observaciones: -->function y = f(x), y = (x+1)/(x^2+x+1), endfunction -->format('v',30) -->[I,err] = intg(0,1,f) err = 0.0000000000000094547263 I= 0.8516060383730911231837 -->integrate('(x+1)/(x^2+x+1)','x',0,1) ans = 0.8516060383730911231837 -->ans - I ans = 0. El programa es bastante fcil de usar, y da una buena precisin. La documentacin dice que intg utiliza dqag0.f y dqags.f de Quadpack. No se algoritmo se da para integrar, pero parece ser la misma. Trat de ajustar la precisin de 30 decimales, pero se niega a mostrar ms de 22, y el ltimo 6 son basura, de todos modos. Obviamente SciLab trabaja en doble precisin en exclusiva. Sin precisin extendida. Hay dos maneras de invocar la rutina de integracin. En un caso, los argumentos son (f, a, b), en el otro caso (a, b, f). Ellos deben ser el mismo.

Observations: The program is fairly easy to use, and gives good accuracy. The documentation says that intg uses dqag0.f and dqags.f from

Problema 2: Serie de Taylor Expansin Queremos saber dos cosas:

quadpack. No algorithm is given for integrate, but it seems to be the same one. I tried to set the accuracy to 30 decimals, but it refuses to display more than 22, and the last 6 are garbage, anyway. Obviously SciLab works in double precision exclusively. No extended accuracy. There are two ways to invoke the integration routine. In one case, the arguments are (f,a,b), in the other case (a,b,f). They should be the same.

1. La serie de Taylor por el pecado (e -1) alrededor del punto x = 0 5 hasta el trmino x 2. La expansin de la diferencia central [f (x + h) - f (x - h)] / (2 h) de una funcin f no especificado (x) en potencias de h. Mathematica

x

En [11]: = Serie [Sin [Exp. [x] -1], {x, 0,5}] Salida [11] = Problem 2: Taylor Series Expansion We want to find two things: 1. The Taylor series for sin(e -1) around the point x=0 up to the x term 2. The expansion of the central difference [f(x+h) - f(x-h)] /(2h) of an unspecified function f(x) in powers of h. Mathematicax 5

En [13]: = trmino1 = Serie [f [x + h], {h, 0,4}] Salida [13] =

In[11]:= Series[Sin[Exp[x]-1],{x,0,5}] Out[11]=

En [14]: = trmino2 = Serie [f [xh], {h, 0,4}] Salida [14] =

In[13]:= term1 = Series[f[x+h],{h,0,4}]

En [15]: = (trmino 1 - trmino2) / (2h)

Out[13]=

Salida [15] =

In[14]:= term2 = Series[f[x-h],{h,0,4}] Out[14]=

Arce

> Serie (sen (exp (x) -1), x = 0,5);

In[15]:= (term1 - term2) / (2h) Out[15]= > Trmino1: = serie (f (x + h), h = 0,4);

> Trmino2: = series (f (xh), h = 0,4);

Maple > S: = (term1 - trmino2) / (2 * h);

> series(sin(exp(x)-1),x=0,5);

> term1 := series(f(x+h),h=0,4);

> term2 := series(f(x-h),h=0,4);

> Simplificar (s);

> s := (term1 - term2)/(2*h);

> Expansin (s);

> simplify(s);

> Cosechadora (s);

> expand(s);

> Recolectar (s, h);

> combine(s); > Normales (s);

> collect(s,h); > Series (s, h = 0,4);

> normal(s);

El ltimo ejemplo muestra por qu trat de aprender de arce dos o tres veces, y dej cada vez: yo no poda convencer a Arce para simplificar el resultado en la forma que yo quera. La simplificacin final (el que efectivamente trabajadas) es cortesa de Olga Ruff. Matlab

>> Taylor (sen (exp (x) -1), 5)

> series(s, h=0,4);

ans = x 1/2 * x ^ 2-5/24 * x ^ 4 >> Syms fxh >> Term1 = taylor ('f (x + h)', h, 4) term1 = f (x) + D (f) (x) * h 1/2 * @ @ (D, 2) (f) (x) * h ^ 2 1/6 * @ @ (D, 3) (f ) (x) * h ^ 3 >> Trmino2 = taylor ('f (xh)', h, 4) trmino2 = f (x)-D (f) (x) * h 1/2 * @ @ (D, 2) (f) (x) * h ^ 2-1/6 * @ @ (D, 3) (f ) (x) * h ^ 3 >> S = (term1 - trmino2) / (2 * h) s= 1/2 * (2 * D (f) (x) * h 1/3 * @ @ (D, 3) (f) (x) * h ^ 3) / h

The last example shows why I tried to learn Maple two or three times, and gave up every time: I just could not convince Maple to simplify the result in the form that I wanted. The final simplification (the one that actually worked) is courtesy of Olga Ruff. Matlab

>> taylor(sin(exp(x)-1),5) ans = x+1/2*x^2-5/24*x^4 >> syms f x h >> term1 = taylor('f(x+h)',h,4) term1 = f(x)+D(f)(x)*h+1/2*@@(D,2)(f)(x)*h^2+1/6*@@(D,3)(f)(x)*h^3 >> term2 = taylor('f(x-h)',h,4) term2 = f(x)-D(f)(x)*h+1/2*@@(D,2)(f)(x)*h^2-1/6*@@(D,3)(f)(x)*h^3 >> s = (term1 - term2)/(2*h) s= 1/2*(2*D(f)(x)*h+1/3*@@(D,3)(f)(x)*h^3)/h

Scilab No pude encontrar nada en Scilab relacionado con expansiones en serie de potencias.

Problema 3: Solucionar un ODE simple Queremos resolver la EDO y '= y +1, con o sin la condicin inicial y (0) = 1. Mathematica

En [8]: = DSolve [y '[x] == y [x] 1, y, x] Scilab Salida [8] = I couldn't find anything in Scilab related to power series expansions.

Problem 3: Solving a Simple ODE We want to solve the ODE y' = y+1, with or without the initial condition y(0)=1. Mathematica En [9]: = DSolve [{y '[x] == y [x] 1, y [0] == 1}, y, x] Salida [9] =

In[8]:= DSolve[y'[x] == y[x]+1, y, x] Arce Out[8]= > Dsolve (D (y) (x) = y (x) 1, y (x)); In[9]:= DSolve[{y'[x] == y[x]+1, y[0] == 1}, y, x] Out[9]= > Dsolve ({D (y) (x) = y (x) 1, y (0) = 1}, y (x));

Matlab Maple Hacemos la solucin numrica, luego la solucin simblica.

> dsolve(D(y)(x) = y(x)+1, y(x));

>> Yprime = inline ('y +1',' t ',' y ') yprime = Funcin en lnea: yprime (t, y) = y +1 >> [T, y] = ode45 (yprime, [0,3], 1);

> dsolve({D(y)(x) = y(x)+1,y(0)=1}, y(x));

Matlab We do the numerical solution first, then the symbolic solution.

>> yprime = inline('y+1','t','y') yprime = Inline function: yprime(t,y) = y+1 >> [t,y] = ode45(yprime,[0,3],1); >> length(t) ans = 45 >> true_y = -1 + 2*exp(t); >> max((y - true_y)./true_y) ans = 1.787437079083398e-006 >> options = odeset('RelTol',1.e-10); >> [t,y] = ode45(yprime,[0,3],1,options); >> length(t) ans = 89 >> true_y = -1 + 2*exp(t); >> max((y - true_y)./true_y) ans =

>> Length (t) ans = 45 >> True_y = -1 + 2 * exp (t); >> Max ((y -. True_y) / true_y) ans = 1.787437079083398e-006 >> Options = odeset ('RELTOL', 1.e-10); >> [T, y] = ode45 (yprime, [0,3], 1, opciones); >> Length (t) ans = 89 >> True_y = -1 + 2 * exp (t); >> Max ((y -. True_y) / true_y) ans = 1.651705715033635e-007 >> Dsolve ('Dy = y +1) ans = -1 + Exp (t) * C1 >> Dsolve ('Dy = y +1',' y (0) = 1 ') ans = -1 2 * exp (t)

Scilab Al igual que antes, slo podemos hacer la solucin numrica, no la solucin simblica.

-> Funcin yprime = f (t, y), yprime = y + 1, endfunction -> Y0 = 1; -> T0 = 0;

1.651705715033635e-007 >> dsolve('Dy = y+1') ans = -1+exp(t)*C1 >> dsolve('Dy = y+1','y(0)=1') ans = -1+2*exp(t)

-> T = 0:0.1:3; -> Y = oda (y0, t0, t, f); -> True_y = -1 + 2 * exp (t); -> Max ((y -. True_y) / true_y) ans = ,0000002201200831737934

Comentarios: Acabo de utilizar el algoritmo predeterminado here (lsoda de ODEPACK), pero muchos algoritmos disponibles. Tambin hay muchas otras opciones que puede configurar. Matlab de forma predeterminada devuelve la solucin a lo que los puntos que se calcul. SciLab insiste en la interpolacin de la solucin a una secuencia de puntos que el usuario tiene que proporcionar.

Scilab As before we can only do the numerical solution, not the symbolic solution.

-->function yprime = f(t,y), yprime = y + 1, endfunction -->y0 = 1; -->t0 = 0; -->t = 0:0.1:3; -->y = ode(y0,t0,t,f); -->true_y = -1 + 2*exp(t); -->max((y - true_y)./true_y) ans = 0.0000002201200831737934

Problema 4: Trazado Queremos representar la funcin 1 / x + e en el intervalo [0.1, 3]. Mathematicax

Comments: I just used the default algorithm here (lsoda from ODEPACK), but many algorithms are available. There are also many other options you can set. Matlab by default returns the solution at whatever points it was computed. SciLab insists on interpolating the solution at a sequence of points the user has to provide. En [17]: Parcela = [1 / x + exp [x], {x, 0,1, 3}]

Problem 4: Plotting We want to plot the function 1/x + e over the interval [0.1, 3]. Mathematicax

In[17]:= Plot[1/x + Exp[x], {x, 0.1, 3}]

Salida [17] = - Grficos -

Arce

> Parcela (1 / x + exp (x), x = 0,1 .. 3);

Out[17]= - Graphics -

Maple

> plot(1/x+exp(x),x=0.1..3);

Matlab

>> X = linspace (0.1,3); >> Y = 1 / x + exp (x).; >> Plot (x, y) Matlab

>> x = linspace(0.1,3); >> y = 1./x + exp(x); >> plot(x,y)

Scilab The code is virtually identical to Matlab, with one strange exception: y=1./x should be the elementwise inverse of x. Scilab instead treated it as y=1/x, which is the least squares solution of yx=1. I had to write it as y=x.\1. The reason is probably that A./B requires A and B to have the same size, and Scilab is not smart enough to expand 1 into a vector of 1s. Matlab used to have the same problem, but at least it gave an error message at that point, instead of quietly doing something different. Looks like a bug in Scilab to me. The plot looks remarkably like Matlab's plot, including the syntax for producing it. I think the syntax for making dotted lines etc. is also the same.

Scilab El cdigo es virtualmente idntica a Matlab, con una excepcin extraa:. Y = 1 / x debe ser el inverso elementwise de x. Scilab en lugar trat como y = 1 / x, que es la solucin de mnimos cuadrados de yx = 1. Tuve que escribir como y = x. \ 1. La razn es probablemente que A. / B requiere de A y B que tienen el mismo tamao y Scilab no es lo suficientemente inteligente como para ampliar 1 en un vector de 1s. Matlab sola tener el mismo problema, pero al menos le dio un mensaje de error en ese punto, en lugar de silencio haciendo algo diferente. Parece un error en Scilab para m. La trama se parece mucho a la trama de Matlab, incluida la sintaxis para producirlo. Creo que la sintaxis para hacer lneas de puntos, etc tambin es el mismo.

-->x = linspace(0.1,3); -->y = x.\1 + exp(x); -->plot(x,y)

-> X = linspace (0.1,3); -> Y = x \ 1 + exp (x).; -> Plot (x, y)

Comparison These are the default figures for all programs. I am sure you can add labels, change the axis limits, etc., for all of them. All of the programs can save the files in a variety of formats (gif, jpg, ps,...). For inclusion into TeX documents, you should save them as .eps files (encapsulated Postscript).

Comparacin Estas son las cifras por defecto para todos los programas. Estoy seguro de que puede agregar etiquetas, cambiar los lmites de los ejes, etc, para todos ellos. Todos los programas se pueden guardar los archivos en una variedad de formatos (gif, jpg, ps, ...). Para su inclusin en documentos TeX, debe guardarlos como archivos. Eps (PostScript encapsulado).

Outputting Fortran or TeX Code We want to convert a formula to Fortran code, C code, or TeX code, for cutting and pasting into a program or TeX document. Mathematica

Salida de Fortran o cdigo TeX Queremos convertir una frmula de cdigo Fortran, cdigo C, o cdigo TeX, para cortar y pegar en un programa o documento TeX. Mathematica

In[21]:= s = 1 + (x^2+1)/Cos[x] Out[21]=

En [21]: = s = 1 + (x ^ 2 1) / Cos [x] Salida [21] =

In[22]:= FortranForm[s] Out[22]//FortranForm= 1 + (1 + x**2)*Sec(x) In[23]:= TeXForm[s] Out[23]//TeXForm= \left(x^2+1\right) \sec (x)+1 In[24]:= CForm[s] Out[24]//CForm= 1 + (1 + Power(x,2))*Sec(x) In[25]:= MathXLForm[s] Out[25]//MathXLForm=

En [22]: = FortranForm [s] Salida [22] / / FortranForm = 1 + (1 + x ** 2) * Sec (x) En [23]: = TeXForm [s] Salida [23] / / TeXForm = \ left (x ^ 2 +1 \ derecho) \ sec (x) 1 En [24]: = cForm [s] Salida [24] / / cForm = 1 + (1 + Power (x, 2)) * Sec (x) En [25]: = MathXLForm [s] Salida [25] / / MathXLForm =

( x 2 + 1 ) sec ( x ) + 1 Arce Maple

( x 2 + 1 ) sec ( x ) + 1

> S: = 1 + (x ^ 2 1) / cos (x);

> s := 1 + (x^2+1)/cos(x);

> Con (CodeGeneration): > Fortran (s, resultname = "s"); > with(CodeGeneration): > Fortran(s, resultname="s"); > C (s, resultname = "s"); > C(s, resultname="s"); > Java (s, resultname = "s"); > Java(s, resultname="s"); > Matlab (s, resultname = "s"); > Matlab(s, resultname="s"); > VisualBasic (s, resultname = "s"); > VisualBasic(s, resultname="s"); > Ltex (s); > latex(s);

Matlab

Matlab

>> Syms x >> S = 1 + (1 + x ^ 2) / cos (x) s= 1 + (1 + x ^ 2) / cos (x) >> Bonita (s) 2 1 + x 1 + -----cos (x) 2 1 + x 1 + -----cos(x) >> Fortran (s) ans = t0 = 1 + (1 + x ** 2) / cos (x) >> Ltex (s) ans = 1 + {\ frac {1 + {x} ^ {2}} {\ cos \ left (x \ derecho)}} >> Ccode (s) ans = t0 = 1.0 + (1.0 + x * x) / cos (x);

>> syms x >> s = 1 + (1+x^2)/cos(x) s= 1+(1+x^2)/cos(x) >> pretty(s)

>> fortran(s) ans = t0 = 1+(1+x**2)/cos(x) >> latex(s) ans = 1+{\frac {1+{x}^{2}}{\cos \left( x \right) }} >> ccode(s) ans = t0 = 1.0+(1.0+x*x)/cos(x);

Scilab Como he mencionado antes, Scilab slo puede hacer las funciones racionales en forma simblica. Aquellos que se puede convertir en TeX, pero no Fortran o C:

Scilab -> P = poli ([1,1], "x", "coeficiente") As I mentioned before, Scilab can only do rational functions in symbolic form. Those can be converted to TeX, but not Fortran or C: p = 1 + x -> Q = poli ([1,0,2], "x", "coeficiente")

-->p = poly([1,1],"x","coef") p = 1 + x -->q = poly([1,0,2],"x","coef") q = 2 1 + 2x -->r = p/q r = 1 + x ----2 1 + 2x -->A = [1,r;2,3] A = 1 1 + x, - ----2 1 1 + 2x 2 3 - 1 1 -->texprint(A) ans = {\pmatrix{ 1&{ 1+x}\over{ 1+2\*x^{2}}\cr 2&

q = 2 1 + 2x -> R = p / q r = 1 + x ----2 1 + 2x -> A = [1, r; 2,3] A = 1 1 + x, -----2 1 1 + 2x

2 3 1 1 -> Texprint (A) ans = {\ {Pmatrix 1 & {1 + x} \ over {1 +2 \ * x ^ {2}} \ cr 2 & 3}

Tambin hay una herramienta para la conversin de una subrutina Scilab a Fortran. Yo no lo probamos. 3}}

There is also a tool for converting a Scilab subroutine to Fortran. I didn't try it.

Last Updated: February 20, 2008