• Tidak ada hasil yang ditemukan

Thư viện số Văn Lang: Programming for Computations - MATLAB/Octave: A Gentle Introduction to Numerical Simulations with MATLAB/Octave

N/A
N/A
Nguyễn Gia Hào

Academic year: 2023

Membagikan "Thư viện số Văn Lang: Programming for Computations - MATLAB/Octave: A Gentle Introduction to Numerical Simulations with MATLAB/Octave"

Copied!
39
0
0

Teks penuh

If we relax the requirement that the integral be exact, and instead look for approximate values, produced by numerical methods, integration becomes a very simple task for any given .x/(!). This rewriting of the integral is based on a selection of integration points, i D n which are distributed on the interval Œa; b. Starting from (3.5), the different integration methods will differ in the way they approach each integral on the right-hand side.

In particular, we want to use an integral that we can calculate by hand so that the accuracy of the approximation methods can be easily assessed. We can therefore calculate the exact value of the integral as V .1/V .0/1:718 (rounded to 3 decimal places for convenience). Strictly speaking, writing of e.g. "the trapezoidal method" only involves the use of a single trapezoid, while "the compound trapezoidal method" is the most correct name when multiple trapezoids are used.

Basically, if you use the flat style for special purposes, you have to retest the implementation of the algorithm after each change to the program.

Fig. 3.1 The integral of v.t / interpreted as the area under the graph of v
Fig. 3.1 The integral of v.t / interpreted as the area under the graph of v

The Composite Midpoint Method

The General Formula

Implementation

Comparing the Trapezoidal and the Midpoint Methods The next example shows how easy we can combine the trapezoidal and

The different methods differ in the way they construct the evaluation pointsxi and the weightswi.

Testing

  • Problems with Brief Testing Procedures
  • Proper Test Procedures
  • Finite Precision of Floating-Point Numbers
  • Constructing Unit Tests and Writing Test Functions

A strong test if we can calculate exact errors is to see how quickly the error goes to zero. In the trapezoidal and midpoint rules, the error is known to depend on n if n2 if n. We can therefore choose a linear function and construct a test function that checks the equality between the exact analytic expression for the integral and the number computed by the implementation of the trapezoidal method.

The idea of ​​a corresponding unit test is then to run the algorithm for some values, calculate the error (the absolute value of the difference between the exact analytical result and that produced by the numerical method) and check that the error has an approximately correct asymptotic behavior. , i.e. that the error is proportional to ton2 in the case of the trapezoidal and midpoint method. Suppose we have a calculationa + band we want to check that the result is what we expect. We see that all the numbers have an inaccurate digit in the 17th decimal place.

As we show below, these tolerances depend on the size of the numbers in the calculations. This is very convenient because you can always check if the code is working. It's a good habit to run a test suite after every edit of source code files.

Below we will write the test functions for each of the three test procedures we proposed: comparison with hand calculations, checking problems that can be solved exactly, and checking convergence rates. Solving the problem without numerical errors We know that the trapezoidal rule is exact for linear integrands. Proving the correct rates of convergence In this case by integration, it is known that the approximation errors in the trapezoidal rule are proportional ton2, which is the number of subintervals used in the composite rule.

Vectorization

The result is the matrix that would be calculated if we ran aorloop over the individualx values ​​and called for each value. Vectorization essentially eliminates this loop in Matlab (ie, the looping overxand application offto eachxvalue is instead performed in a library of fast, compiled code). Vectorizing the midpoint rule The goal of vectorizing midpoint and trapezoidal functions is also to remove the explicit loop in Matlab.

Since the Matlab implementation of the math function f works with an array argument, which requires array versions of arithmetic operators (.+,.*, etc.) in Matlab, f(x) will produce all the function values ​​in an array. This sum must be multiplied by the rectangle width h to produce the integral value. Note the need for the vectorized operator.*in the function the expression sincev(x) will be called with array argumentsx.

The vectorized code executes all loops very efficiently in compiled code, resulting in much faster execution. Moreover, many readers of the code will also say that the algorithm looks clearer than in the loop-based implementation. If we dose(f(x)), we get the endpoints f(a) and f(b) with unit weight instead of half.

Measuring Computational Speed

Double and Triple Integrals

The Midpoint Rule for a Double Integral

2 Cj hy/ : (3.25) Direct derivation Formula (3.25) can be derived directly even in the two-dimensional case by applying the idea of ​​the midpoint method. The idea of ​​the midpoint method is to approximate a constant over each cell and evaluate the constant at the midpoint. With this function, which is available in filemidpoint_double1.m, we can now calculate some integralR2.

Reusing code for one-dimensional integrals It is very natural to write a two-dimensional midpoint method as we did in functionmidpoint_double1 when we have formula (3.25). However, we can alternatively ask, as we did in mathematics, whether we can reuse a well-tested implementation for one-dimensional integrals to compute double integrals. The answer is yes, if we think as we did in mathematics: calculate the double integral as the midpoint rule for integriming.x/and define.

The important advantage of this implementation is that we reuse a well-tested function for the standard one-dimensional midpoint rule and we apply the one-dimensional rule exactly as in mathematics. The midpoint rule is exact for linear functions, no matter how many subintervals we use. We can choose .x; y/D2xCy and create a good test function that can automatically verify our two alternative implementations of the two-dimensional midpoint rule.

Since a test function should have no print statement, we simply comment it out as we did in the function above. The derivation of a formula for the double integral and the implementations follow exactly the same ideas as we explained with the midpoint method, but there are more expressions to write in the formulas. This exercise is a very good test of your understanding of the mathematical and programming ideas in this section.

The Midpoint Rule for a Triple Integral

However, it's somewhat annoying to have a function that's completely silent when it works - are we sure all things are calculated correctly? It is therefore strongly recommended to include a print statement during development so that we can monitor the calculations and be confident that the test function does what we want. 2hzCkhz/ : (3.26) Note that we can apply the ideas under Direct Derivation at the end of Section 3.7.1 to arrive directly at (3.26): divide the domain intonxnynz cells by volumes hxhyhz; approximated by a constant, evaluated in the middle.xi; yy; zk/, in each cell; and list the cell integralshxhyhzg.xi; yy; zk/.

Implementation We follow the ideas for the implementation of the midpoint rule for a double integral. The corresponding functions are shown below and can be found in the midpoint_triple1.m,midpoint.m,midpoint_triple2.m, test_midpoint_triple.m files.

Monte Carlo Integration for Complex-Shaped Domains Repeated use of one-dimensional integration rules to handle double and triple inte-

However, if we assume that the fraction of A.R/occupied by A.˝ is the same as the fraction of arbitrary points inside˝, we get a simple estimate for A.˝/. To get an idea of ​​the method, consider a circular domain, embedded in a rectangle, as shown below. The correct answer is 3, but the Monte Carlo integration is unfortunately never exact, so it is impossible to predict the outcome of the algorithm.

We only know that the estimated integral should approach 3 as the number of random points goes to infinity. Also, for a given number of points, the algorithm can be run several times and get different numbers that fluctuate around the exact value, since different sample points are used in different calls of the Monte Carlo integration algorithm. To get a one-line definition of g, we took advantage of the fact that each of the boolean tests (in parentheses separated by &&) will evaluate to 0 (if false) or 1 (if true).

On the other hand, if any one of the Boolean tests evaluates to false, the parentheses will evaluate to 0 and the number1 (from1C2 0) is returned. It is known mathematically that the standard deviation of the Monte Carlo estimate of an integral converges asn1=2, where is the number of samples. Test function for function with random numbers To make a test function, we need a unit test that has identical behavior every time we run the test.

Provided that the test function always uses this seed, we should get exactly this result whenever theMonteCarlo_doublefunction is called. As in the case of the test above, we experience better results with a larger number of points. When we have such evidence of a functional implementation, we can turn the test into a proper test function.

Hand calculations for the trapezoidal method

Hand calculations for the midpoint method

Hand-calculations with sine integrals We consider integrating the sine function: R b

Make test functions for the midpoint method

Explore rounding errors with large numbers

Rectangle methods

Adaptive integration

The integrandxx has no anti-derivative that can be expressed in terms of standard functions (visit http://wolframalpha.com and typeintegral(x^x,x) to convince yourself that our statement is correct. Note that Wolfram alpha u there is an answer, but that answer is an approximation, it is not exact.This is because Wolfram alpha also uses numerical methods to arrive at the answer, just like you will do in this exercise).

Integrate products of sine functions In this exercise we shall integrate

Revisit fit of sines to a function

Minimization of E with respect to b1; : : : ; bN will give us abest approximation, in the sense that we adaptb1; : : : ; bN. such that SN deviates from as little as possible. A remarkable property of the trapezoidal rule is that it is exact for integralR sinnt dt (when subintervals are of equal size). Use this property to create a function test_integrate_coeff to verify the implementation of integrate_coeffs. e) Implement the choice f .t / D 1t as a Matlab function f(t) and call integrate_coeffs(f, 3, 100) to see what the optimal choice of b1; b2; b3is. f) Make a function plot_approx(f, N, M, filename) where you plotf(t) together with the best approximationSN calculated as above, using M intervals for numerical integration.

Derive the trapezoidal rule for a double integral

Gambar

Fig. 3.1 The integral of v.t / interpreted as the area under the graph of v
Fig. 3.2 Computing approximately the integral of a function as the sum of the areas of the trape- trape-zoids
Fig. 3.3 Computing approximately the integral of a function as the sum of the areas of the rect- rect-angles
Fig. 3.4 Illustration of the rectangle method with evaluating the rectangle height by either the left or right point

Referensi

Dokumen terkait

6.2 Newton’s Method 191 A fundamental idea of numerical methods for nonlinear equations is to construct a series of linear equations since we know how to solve linear equations and