Search This Blog

Tuesday, January 15, 2013

How to start Haskell on ubuntu

Haskell in 5 steps

Haskell is a general purpose, purely functional programming language. This page will help you get started as quickly as possible.

Contents

[hide]


1 Install Haskell

The recommended way to get started with programming Haskell is the Haskell Platform. The Platform comes with GHC, the de-facto standard Haskell compiler, with many useful tools that will let you program Haskell painlessly. The installation should be easy and simple enough on most operating systems.
Try Haskell provides a less complete but quicker way to give Haskell a shot.

2 Start Haskell

If you have installed the Haskell Platform, open a terminal and type ghci (the name of the executable of the GHC interpreter) at the command prompt. Alternatively, if you are on Windows, you may choose WinGHCi in the Start menu.
    $ ghci
    GHCi, version 6.12.3: http://www.haskell.org/ghc/  :? for help
    Loading package base ... linking ... done.
    Prelude>
And you are presented with a prompt. The Haskell system now attentively awaits your input.

3 Write your first Haskell program

If you've learned to program another language, your first program probably was "Hello, world!", so let's do that:
Prelude> "Hello, World!"
"Hello, World!"
The Haskell system evaluated the string, and printed the result. Or we can try a variation to print directly to standard output:
Prelude> putStrLn "Hello World"
Hello World
Using a Haskell compiler, such as GHC, you can compile the code to a standalone executable. Create a source file hello.hs containing:
main = putStrLn "Hello, World!"
And compile it with:
    $ ghc -o hello hello.hs
You can then run the executable (./hello on Unix systems, hello.exe on Windows):
    $ ./hello
    Hello, World!

4 Haskell the calculator

Let's do something fun. In Haskell, your first true program is the factorial function. So back to the interpreter now and let's define it:
Prelude> let fac n = if n == 0 then 1 else n * fac (n-1)
This defines a new function called fac which computes the factorial of an integer.
We can now run fac on some argument:
Prelude> fac 42
1405006117752879898543142606244511569936384000000000
Congratulations! Programming made easy. Note that if you're using Hugs, you'll need to load the definition of fac from a file, fac.hs, containing:
fac n = if n == 0 then 1 else n * fac (n-1)
And run it with Hugs as follows (this also works in GHCi):
Hugs.Base> :load fac.hs
Main> fac 42
1405006117752879898543142606244511569936384000000000
We can of course compile this program, to produce a standalone executable. In the file fac.hs we can write (and let's use elegant pattern matching syntax just for fun):
fac 0 = 1
fac n = n * fac (n-1)
 
main = print (fac 42)
which can then be compiled and run:
    $ ghc -o fac fac.hs
    $ ./fac
    1405006117752879898543142606244511569936384000000000
Great!

4.1 Write your first parallel Haskell program

Haskell has good support for parallel and multicore programming. We can write a parallel program by adding `par` to expressions, like so:
import Control.Parallel
 
main = a `par` b `par` c `pseq` print (a + b + c)
    where
        a = ack 3 10
        b = fac 42
        c = fib 34
 
fac 0 = 1
fac n = n * fac (n-1)
 
ack 0 n = n+1
ack m 0 = ack (m-1) 1
ack m n = ack (m-1) (ack m (n-1))
 
fib 0 = 0
fib 1 = 1
fib n = fib (n-1) + fib (n-2)
Compiling with -threaded and optimizations on:
$ ghc -O2 --make A.hs -threaded -rtsopts
[1 of 1] Compiling Main             ( A.hs, A.o )
Linking A ...
Note that in versions of GHC prior to GHC 7, you can leave off the -rtsopts flag
And now we can run our multicore program. Here across two cores:
$ time ./A +RTS -N2
1405006117752879898543142606244511569936384005711076
./A +RTS -N2  2.14s user 0.02s system 149% cpu 1.449 total
Congratulations! You are now programming your multicore!

5 Where to go from here

There are many good Haskell tutorials and books. Here are some we recommend:
Tutorials
For a complete list of textbooks, references and tutorials:
Join the community!
Talk to others in the Haskell community.
Languages: de tur zh/cn zh/tw ja

How to install GHC on Ubuntu

#Install prerequisites
sudo aptitude install ghc darcs zlib1g-dev libncurses5-dev
#Get GHC 7.4.1 source and cabal-install HEAD
wget http://www.haskell.org/ghc/dist/7.4.1/ghc-7.4.1-src.tar.bz2
darcs get --lazy http://darcs.haskell.org/cabal/
 
tar xjf ghc-7.4.1-src.tar.bz2
cd ghc-7.4.1
./configure --prefix=$HOME/src/ghc
time make -j9 #Only took me about 19 minutes on recent quad core xeon
make install
 
echo "export PATH=`pwd`/bin:$HOME/.cabal/bin:$PATH" >> ~/.bashrc
#my bashfu might be off here, but you get the idea
. ~/.bashrc
 
mv ~/.cabal ~/.cabalold
cd ../cabal/cabal-install
export EXTRA_CONFIGURE_OPTS="-p"
./bootstrap
 
cabal update
#Edit ~/.cabal/config to set library profiling to True
 
#Test everything up until now
ghc --version
cabal --version
 
#to pull your own 'haskell platform' try the following
cabal install haskell-src html mtl parallel parsec \
regex-base regex-compat regex-posix stm syb text \
transformers vector --solver=modular
#I had to leave out GLUT, OpenGL, fgl, QuickCheck, and cgi
#to overcome some MonadCatchIO based dependency errors
 
 
 
In order to get Pandoc and some of the other stuff I need try this
cabal install vector-strategies vector-fftw fgl graphviz
# In the future instead of the below I think I'll be able to do...
# cd ~/src
# cabal unpack pandoc-types
# cd pandoc-types
# Here I had to edit Text/Pandoc/Builder.hs to hide ((<>)) from Data.Monoid
cabal install pandoc Graphalyze
Also I need to email the maintainers of Graphalyze and gnuplot about the changes I had to make to get it to compile with GHC 7.4.1.
 

Installing the Haskell Platform in Ubuntu

Installing the Haskell Platform in Ubuntu

First things first, lets get the dependencies out of the way.
1sudo apt-get install libedit2 libedit-dev freeglut3-dev libglu1-mesa-dev
Now let’s remove any haskell packages we may have installed, as these will cause conflicts.

1sudo apt-get autoremove ghc6
Note that if you installed cabal as per my previous post, you can remove the executable from your $PATH by executing the following:

1sudo rm /usr/local/sbin/cabal

This will not delete the executable, which is stored in $HOME/.cabal/bin/. This just removes the sym-link that was in your $PATH. Next, lets grab the source for GHC 6.10.3 (which is required to build the Haskell Platform)

and untar it.

next, lets configure it and build it:

1cd ghc-6.10.3/
2./configure
3sudo make install
After this, installing the Haskell Platform is just more of the same:

01#grab the tarball
03 
04# untar it
06 
07 
08# ... and install it.
09cd haskell-platform-2009.2.0.1/
10./configure
11make
12sudo make install
Along the way, the install scripts for the Haskell Platform will give you prompts for the next step to take.
Enjoy your Haskell Platform, and happy developing!

Haskell Platform for Linux

< Home
Community-supported versions of the Haskell Platform on Linux and Unix
These distributions offer the Haskell Platform in their package repositories. You can easily install the Haskell Platform through your distribution's native package manager.
Ubuntu Debian Fedora
Arch Linux Gentoo NixOS
OpenBSD FreeBSD Mint
Information for other systems
openSUSE Mandriva
See also: justhub, for REHL, CentOS, Scientific Linux, and Fedora spport

Build from source

Download the source tarball for Unix-like systems: here
Get and install GHC 7.4.2 prior to building the platform:
Finally, unpack the Haskell Platform source tarball, and run (possibly with 'sudo'):
    ./configure
    make
    make install
You may pass --prefix flag to ./configure to change the default install path.
There is also a README file in the tarball with more detailed information on building.

Prior releases

Haskell Platform for Linux

Haskell Platform
http://www.haskell.org/platform/
================================
 Download Link : http://www.haskell.org/platform/linux.html

This is the source tarball for Haskell Platform. It contains the source and
build files for all the packages that make up the platform, beyond those that
come with GHC.

If your OS has a pre-built distribution of Haskell Platform, that is likely to
be a much easier way than building the platform yourself. The Haskell Platform
web site (see above URL) contains builds for Mac OS X and Windows that include
everything you need, including GHC.

The web site also contains links for those Linux distributions for which there
is a pre-build version. In most cases, that version of the platform is availble
through the normal package manager for the distribution, rather than directly
from the Haskell Platform web site.



Preparation
-----------
You will need to have GHC 7.4.2 installed prior to building the platform.
Please see:
    http://www.haskell.org/ghc/download_ghc_7_4_2

Note that the warning at top will tell you to consider installing the
platform instead. If you've gotten this far, you can ignore that.

You can use a different version of GHC, but it may not work.


You will also need the developer packages for various standard system libraries,
such as zlib and GLUT. Exactly which packages you need will differ based on
the OS distribution you use. In general, if you get an error during the build
process that a library is missing, look it up in your package manager. You will
need both the library and the development package for the library.


Build and Install
-----------------
In this directory, run:

    ./configure

This is standard autoconf, so options like --prefix will work. Run with --help
to see all the options. In particular, if you are using a different versino of
GHC, you'll need to add --enable-unsupported-ghc-version.

Now build the packages:

    make

Finally, to install everything, use

    make install

Note that you will probably have to run this command 'sudo'.

Install Glasgow Haskell Compiler GHC on Ubuntu

Download GHC

http://www.haskell.org/ghc/download_ghc_7_4_2#x86linux 



This is the INSTALL instructions for a binary distribution of GHC. For
more details on what on earth this package is up to, please consult
the README and ANNOUNCE.

This distribution can be installed in a location of your choosing.

To set the ball rolling, run the configure script (as usual, run the
script with --help to see what options it supports).  eg. to set up
the package for installing in directory , use

    ./configure --prefix=

The default installation directory is /usr/local.

The configure script will figure out what platform you're running on,
and a couple of other interesting pieces of trivia, which it will then
fill in the Makefile.in template to give you a real Makefile.  If
you're of a paranoid persuasion, you might want to take a look at this
Makefile to see if the information is correct.

Now run:

    make install

(`make show-install-setup' prints the details of where the different
pieces of the bundle are heading when -- possibly helpful).

For more information, full GHC documentation is available from the
main GHC site:

  http://www.haskell.org/ghc

Bug reports/suggestions for improvement to the installation
procedure/setup (as well as other GHC related troubles you're
experiencing, of course), gratefully received.  Bug reporting
instructions are here:

  http://www.haskell.org/ghc/reportabug

Enjoy,
-- The GHC Team.

Saturday, January 05, 2013

Linked Lists in C++

Linked Lists in C++


General
Basically, a linked list is a collection of nodes. Each node in the list has two components – a components to store information about that node (i.e. data) and a component to store the next “linked” node. The last node in a linked list indicates that it does not have a “linked” node – usually by a null reference. The address of the first node is stored in a separate location, called the head or first.

singlelinkedlist
The code snippet below shows a basic structure of a node declaration in c++.
struct nodeType
{
    int data;
    nodeType *link;
};

The variable declaration is as follows…
nodeType *head;

Basic Operations of a Linked List
There are a few basic operations that are typically needed with a linked list
  • Search a list to determine whether a particular item is in the list
  • Insert an item in the list
  • Delete an item from the list
Traversing/Searching a List
To traverse a linked list you need some way to move around the list. The *head is a pointer in the list, but you cannot use it to traverse the list because then you would loose a reference to the beginning of the list.
Typically to traverse the list, you will need to declare another pointer that follows the same declaration as head, but that is not critical if you change where it’s pointing to…
current = head;
while (current != NULL)
{
    cout << current->data << " ";
    current = current->link;
}

Item Insertion and Deletion
To insert a new node into a linked list, you need to do the following:
  • Create a new node
  • Determine the position in the list that you want to insert it and assign it to current
  • Make the new node is point to the same link that current is pointing to
  • Make current now point to the new node
In code, assuming current was at the correct position, then it would look something like this…
nodeType *newNode;

newNode = new nodeType;
newNode->data = 123;
newNode->link = current->link;
current->link = newNode;

To delete a node from a linked list, you need to do the following:
  • Determine the node that you want to remove and point current to the node prior to that node
  • Create a pointer to point to the node you want to delete (i.e. *p)
  • Make current’s link now point to p’s link
  • delete p from memory
In code, assuming current was at the correct position, then it would look something like this…
deleteNode = new nodeType;
deleteNode = current->link;
current->link = deleteNode->link;
delete deleteNode;
Building a Linked List
There are two main ways to build a linked list, forward and backward.
I find the best way to explain this approach is code…. below if the forward approach, meaning the node is inserted forwards – i.e. at the back of the list…
int main()
{
    //
    // Init the list
    //
    nodeType *first;
    nodeType *last;
    nodeType *newNode;
    int num;

    first = NULL;
    last = NULL;

    //
    // Build the list the forward approach
    //
    for (int i=0; i<3 cout="cout" i="i" span="span" style="color: #a31515;">"Enter number :"
; cin >> num; newNode = new nodeType; // Create the new node newNode->data = num; // and assign its data value newNode->link = NULL; // make its link point to nothing if (first == NULL) // If there is nothing in the list, then make the { // newNode the first item and the last item first = newNode; last = newNode; } else // Else if first already has a value { // make the last item link to the newNode last->link = newNode; // and make newNode the last item last = newNode; } } // // Display the list // DisplayList(first); system("PAUSE"); return(0); }
If you look at the forward approach, you need two pointers to maintain the list – first & last. This is because you don’t want to traverse the list each time you want to add something. The backward way of building a list in my opinion is easier to read and code since you only need to worry about the head of the list. The code implementation is listed below…
//
// Init the list
//
nodeType *head;    
nodeType *newNode;
int num;
head = NULL;    

//
// Build the list using the backward approach
//
for (int i=0; i<3 cout="cout" i="i" span="span" style="color: #a31515;">"Enter number :"
; cin >> num; newNode = new nodeType; // Create the new node newNode->data = num; // and assign its data value newNode->link = head; // make its link point to the front of the list head = newNode; // make the head now be the newNode } Sorted & Unsorted Linked Lists
Typically there are two types of linked lists, those that are sorted and those that are unsorted.
The advantages of knowing that a collection of data is sorted when performing searches greatly reduces the complexity of the search algorithms as well as improving the searches performance.
Typically to maintain a sorted listed requires adjusting the insert method so that when a list is being built, the order is maintained.
Doubly Linked Lists
A doubly linked list is a linked list that every node has its “next” and “previous” node stored.
The advantages of a doubly linked list are that it can be traversed in any direction, which can be beneficial when performing iterations on the list.
The basic structure of a doublelinkedlist node is shown below…
struct doublenodeType
{
    int data;
    nodeType *next;
    nodeType *previous;
};

Circular Linked Lists
As the name suggest, a circular linked lists is one where the first node points to the last node of the list.

Calculus with MATLAB

Calculus with MATLAB

copyright © 2011 by Jonathan Rosenberg based on an earlier web page, copyright © 2000 by Paul Green and Jonathan Rosenberg

Contents

In this published M-file we will try to present some of the central ideas involved in doing calculus with MATLAB. The central concept is that of a function. We will discuss first the representation of functions and then the ways of accomplishing the things we want to do with them. These fall into three broad categories: symbolic computation, numerical computation, and plotting, and we will deal with each of them in turn. We will try to provide concrete illustrations of each of the concepts involved as we go along. For the present, we will confine ourselves to functions of one variable. Later, we will need to discuss MATLAB's routines for dealing with functions of several variables.

Functions and Symbolic Differentiation

There are two distinct but related notions of function that are important in Calculus. One is a symbolic expression such as sin(x) or x^2. The other is a rule (algorithm) for producing a numerical output from a given numerical input or set of numerical inputs. This definition is more general; for example, it allows us to define a function f(x) to be x^2 in case x is negative or 0, and sin(x) in case x is positive. On the other hand, any symbolic expression implies a rule for evaluation. That is, if we know that f(x) = x^2, we know that f(4) = 4^2 = 16. In MATLAB, the fundamental difference between a function and a symbolic expression is that a function can be called with arguments and a symbolic expression cannot. However, a symbolic expression can be differentiated symbolically, while a function cannot. MATLAB functions can be created in three ways:
  • as anonymous functions or function handles (we learned about these in the last lesson, though without discussing what is "anonymous" about them, which is the fact that they can be used without naming them),
  • as function M-files, and
  • as inline functions (not especially recommended).
A typical way to define a symbolic expression is as follows:
syms x
f = x^2 - sin(x)
 
f =
 
x^2 - sin(x)
 
The next lines will show that we can differentiate f, but we cannot evaluate it, at least in the obvious way, since f(4) will give an error message (try it!). Notice that MATLAB recognizes what the "variable" is. In the case of several symbolic variables, we can specify the one with respect to which we want to differentiate.
diff(f)
 
ans =
 
2*x - cos(x)
 
We can evaluate f(4) by substituting 4 for x, or in other words, by typing
subs(f,x,4)
ans =

   16.7568

There are a few ways to convert f to a function. One is to define
fanon = @(t) subs(f, x, t)
fanon(4)
fanon = 

    @(t)subs(f,x,t)


ans =

   16.7568

What is going on here is that the x in f gets replaced by whatever the argument to the function is.
We can also turn f into an inline function with the command:
fin=inline(char(f))
fin =

     Inline function:
     fin(x) = x^2 - sin(x)

What's going on here is that the inline command requires a string as an input, and char turns f from a symbolic expression to the string 'x^2-sin(x)'. (If we had simply typed fin=inline(f) we'd get an error message, since f is not a string.) The inline function fin now accepts an argument:
fin(4)
ans =

   16.7568

Finally, there is another possible syntax:
ff = @(x) eval(vectorize(f))
ff = 

    @(x)eval(vectorize(f))

What's going on here is that vectorize is like char, though it is more flexible in that it will produce a string that can take a vector input. Then eval evaluates the resulting string. The result is a function that will operate on a vector input, as follows:
ff([0,pi])
ans =

         0    9.8696

Similarly we can construct a function, either inline or anonymous, from the derivative of f:
fxin=inline(char(diff(f)))
fxin =

     Inline function:
     fxin(x) = 2*x - cos(x)

Here the matlab function char replaces its argument by the string that represents it, thereby making it available to functions such as inline that demand strings as input.
Alternatively, we can try:
fxanon = @(t) subs(diff(f), x, t)
fxanon(4)
fxanon = 

    @(t)subs(diff(f),x,t)


ans =

    8.6536

The other way to create a function that can be evaluated is to write a function M-file. This is the primary way to define a function in most applications of MATLAB, although we shall be using it relatively seldom. The M-file can be created with the edit command, and you can print out its contents with the type command.
type fun1
function out=fun1(x)
out=x^2-sin(x);
fun1(4)
ans =

   16.7568

Problem 1:

Let
$$g(x) = x(e^x - x - 1).$$
  • a) Enter the formula for g(x) as a symbolic expression.
  • b) Obtain and name a symbolic expression for g'(x).
  • c) Evaluate g(4) and g'(4), using subs.
  • d) Evaluate g(4) and g'(4), by creating anonymous functions.
  • e) Evaluate g(4) by creating an M-file.

Graphics and Plotting.

One of the things we might want to do with a function is plot its graph. MATLAB's most elementary operation is to plot a point with specified coordinates.
plot(4,4)
The output from this command is the faint blue dot in the center of the figure. The way MATLAB plots a curve is to plot a sequence of dots connected by line segments. The input for such a plot consists of two vectors (lists of numbers). The first argument is the vector of x-coordinates and the second is the vector of y-coordinates. MATLAB connects dots whose coordinates appear in consecutive positions in the input vectors. Let us plot the function we defined in the previous section. First we prepare a vector of x-coordinates:
X1=-2:.5:2
X1 =

  Columns 1 through 7

   -2.0000   -1.5000   -1.0000   -0.5000         0    0.5000    1.0000

  Columns 8 through 9

    1.5000    2.0000

X1 is now a vector of nine components, starting with -2 and proceeding by increments of .5 to 2. Generally speaking, any command such as the one above creating a long vector should be terminated by a semicolon, to suppress the annoying written output.
We must now prepare an input vector of y-coordinates by applying our function to the x-coordinates. Our function fin will accomplish this, provided that "vectorize" it, i.e., we redefine it to be able to operate on vectors.
The matlab function vectorize replaces , ^, and / by ., .^, and ./ respectively. The significance of this is that MATLAB works primarily with vectors and matrices, and its default interpretation of multiplication, division, and exponentiation is as matrix operations. The dot before the operation indicates that it is to be performed entry by entry, even on matrices, which must therefore be the same shape. There is no difference between the dotted and undotted operations for numbers. However vectorized expressions are not interpreted as symbolic, in the sense that they cannot usually be symbolically differentiated. Fortunately, it is never necessary to do so.
fin=inline(vectorize(f))
Y1=fin(X1)
plot(X1,Y1)
fin =

     Inline function:
     fin(x) = x.^2 - sin(x)


Y1 =

  Columns 1 through 7

    4.9093    3.2475    1.8415    0.7294         0   -0.2294    0.1585

  Columns 8 through 9

    1.2525    3.0907

This plot is somewhat crude; we can see the corners. To remedy this we will decrease the step size. We will also insert semicolons after the definitions of X1 and Y1 to suppress the output.
X1=-2:.02:2;
Y1=fin(X1);
plot(X1,Y1)
Actually, the plotting of a symbolic function of one variable can be accomplished much more easily with the command ezplot, as in "Introduction to MATLAB". However, plot allows more direct control over the plotting process, and enables one to modify the color, appearance of the curves, etc. (Type doc plot for more on this.)

Problem 2:

Let the function g be as in Problem 1.
  • a) Plot g(x) for x between -3 and 3 using plot and a small enough step size to make the resulting curve reasonably smooth.
  • b) Plot g using ezplot.
  • c) Combine the previous plot with a plot of x^2 + 1. Plot enough of both curves so that you can be certain that the plot shows all points of intersection.

Solving Equations

The plot of f indicates that there are two solutions to the equation f(x) = 0, one of which is clearly 0. We have both solve, a symbolic equation solver, and fzero, a numerical equations solver, at our disposal. Let us illustrate solve first, but with an easier example.
g = x^2 - 7*x + 2
groots = solve(g)
 
g =
 
x^2 - 7*x + 2
 
 
groots =
 
 41^(1/2)/2 + 7/2
 7/2 - 41^(1/2)/2
 
Here solve finds all the roots it can, and reports them as the components of a column vector. Ordinarily, solve will solve for x, if present, or for the variable alphabetically closest to x otherwise. In the next example, y specifies the variable to solve for. Notice also that the first argument to solve is a symbolic expression, which solve sets equal to 0.
syms y
solve(x^2+y^2-4, y)
 
ans =
 
  (2 - x)^(1/2)*(x + 2)^(1/2)
 -(2 - x)^(1/2)*(x + 2)^(1/2)
 
Unfortunately, solve will not work very well on our function f, and may even cause MATLAB to hang. Let us try fzero instead, which solves equations numerically, using something akin to Newton's method, starting at a given initial value of the variable. The command fzero will not accept f as an argument, but it will accept the construct @fun1 (the @ is a marker for a function name) or an anonymous function.
newfroot=fzero(char(f),.8)
newfroot=fzero(fin,.8)
newfroot=fzero(@fun1,.8)
newfroot =

    0.8767


newfroot =

    0.8767


newfroot =

    0.8767

Problem 3:

Let g be as in Problems 1 and 2.
  • a) Referring to the plot in part c) of Problem 2, estimate those values of x for which g(x) = x^2 + 1.
  • b) Use solve to obtain more precise values and check the equation g(x) = x^2 + 1 for those values.

Symbolic and Numerical Integration

We have not yet dealt with integration. MATLAB has a symbolic integrator, called int, that will easily integrate f.
intsf=int(f,0,2)
 
intsf =
 
cos(2) + 5/3
 
However, if we replace f by the function h, defined buy
h=sqrt(x^2-sin(x^4))
 
h =
 
(x^2 - sin(x^4))^(1/2)
 
then int will be unable to evaluate the integral.
int(h,0,2)
Warning: Explicit integral could not be found. 
 
ans =
 
int((x^2 - sin(x^4))^(1/2), x = 0..2)
 
However, if we type double (standing for double-precision number) in front of the integral expression, MATLAB will return the result of a numerical integration.
double(int(h,0,2))
Warning: Explicit integral could not be found. 

ans =

    1.7196

We can check the plausibility of this answer by plotting h between 0 and 2 and estimating the area under the curve.
ezplot(h,[0,2])
The numerical value returned by MATLAB is somewhat less than half the area of a square 2 units on a side. This appears to be consistent with our plot.
The numerical integration invoked by the combination of double and int is native, not to MATLAB, but to the symbolic engine MuPAD powering the Symbolic Math Toolbox. MATLAB also has its own numerical integrator called quadl. (The name comes from quadrature, an old word for numerical integration, and the "*l*" has something to do with the algorithm used, though there's no need for us to discuss it here.) The routines double(int(?)) and quadl(?) give slightly different answers, though usually they agree to several decimal places.
quadl(@(x) eval(vectorize(h)),0,2)
ans =

    1.7196

Problem 4:

Let g be as in previous problems.
  • a) Evaluate
$$\int_{0}^3 g(x)\,dx$$
symbolically, using int, and numerically using quadl. Compare your answers.
  • b) Evaluate
$$\int_0^3 \sqrt{1 + (g'(x))^2}\,dx,$$
both using int and double, and using quadl.
  • c) Check the plausibility of your answers to part b) by means of an appropriate plot.

Additional Problems

1. Let
$$f(x) = x^5 + 3x^4 - 3x + 7.$$
  • a) Plot f between x = -1 and x = 1.
  • b) Compute the derivative of f.
  • c) Use solve to find all critical points of f.
  • d) Find the extreme values of f on the interval [-1,1]. Hint: solve will store the critical points in a vector, which you cannot use unless you name it. Remember that you also need the values of f at 1 and -1.
2. Find all real roots of the equation x = 4 sin(x). You will need to use fzero.
3. Evaluate each of the following integrals, using both int and quadl.
  • a)
$$\int_0^\pi \sqrt{1 + \sin^2(x)}\,dx$$
  • b)
$$\int_0^\pi \sqrt{1 + \sin^4(x)}\,dx$$