PHYSICS 115/242 Homework 2, Solutions
|
|
- Lucas Rich
- 6 years ago
- Views:
Transcription
1 PHYSICS 115/242 Homework 2, Solutions 1. Trapezium Rule I wrote a function trap to do the trapezoidal rule, and put it in a separate file, trap.c. This is as follows: /****************************************************************** * File: trap.c * * usage: trap(f, a, b, n) * * where f(x) is the the function to be integrated using the * trapezium rule * a is the lower limit * b is the upper limit * n is the number of intervals * To use: repeatedly call the routine, doubling n each time until * the desired accuracy has been reached. *****************************************************************/ double trap (double f(double), double a, double b, int n) double h, sum; int i; h = (b - a) / n; // set stepsize sum =.5 * (f(a) + f(b)); // initialize sum with end points, factor 1/2 for (i = 1; i < n; i++) sum += f(a + i * h); // intermediate points return h * sum; // return answer Note that declaration of f should really be as a pointer to a function, i.e. double trap (double (*f)(double), double a, double b, int n) but having f(double) rather than double (*f)(double) also works. I then wrote a program, call trap.c, to call trap as follows: #include <math.h> #include <stdio.h> double f(double x) // define function to be integrated 1
2 return 1 / (1 + x); main() double x, a, b, h, exact, ans, trap(); int i, n, iter, ITERMAX; exact = log((double) 2); ITERMAX = 8; b = 1.; a = ; // exact answer // set no. of iterations // set upper limit // set lower limit printf (" h ans (exact-ans)/h^2 \n"); n = 1; for (iter = ; iter < ITERMAX; iter++) // keep doubling no. of intervals h = (b - a)/n; ans = trap(f, a, b, n); n *= 2; // double n for next iteration printf ("%12.5f %12.5f %12.5f \n", h, ans, (ans - exact)/(h*h)); The two files trap.c and call trap.c compiled together with the command gcc trap.c call_trap.c The code is executed with the command./a.out. The resulting output is: OUTPUT h ans (exact-ans)/h^ The exact answer is ln2 =
3 From the last column we see that for small h the error is equal to.625h 2 = h 2 /16. From the theory, the coefficient of h 2 is predicted to be 1 12 [f (b) f (a)] = 1 ( 14 ) = 1 16, as found numerically. 2. Simpson s Rule As in the previous question I wrote a function to do the integration, simp and put this in a separate file simp.c. /****************************************************************** * File: simp.c * * usage: simp(f, a, b, n) * * where f(x) is the the function to be integrated using Simpson s rule. * a is the lower limit. * b is the upper limit. * n is the number of intervals. * Note: n must be even. A better code would check for this. * To use: repeatedly call the routine, doubling n each time until * the desired accuracy has been reached. *****************************************************************/ double simp (double f(double), double a, double b, int n) double h, sum1, sum2; int i; if (n%2!= ) printf("\n ERROR in simp.c. No. of intervals must be even.\n\n"); exit(1); h = (b - a) / n; // set stepsize sum1 = ; sum2 = ; // initialization for (i = 1; i < n; i+=2) sum1 += f(a + i*h); // odd points for (i = 2; i < n; i+=2) sum2 += f(a + i*h); // even points return h*(4*sum1 + 2*sum2 + f(a) + f(b))/3; //include first //and last points and return answer I then called this routine with the following code: #include <math.h> #include <stdio.h> 3
4 double f(double x) return exp(-x) * sin(x); // define function to be integrated main() double x, a, b, h, ans, prevans, EPS; double simp(); int i, n, iter, count, ITERMAX; ITERMAX = 15; // set no. of iterations b = 2.; // set upper limit a = ; // set lower limit EPS = 1.e-8; // set desired precision prevans = 1.e+1; ans = ; // initially set "previous answer" to // a ridiculous value // print header printf (" h ans ans-prevans (ans-prevans)/h^4 \n"); n = 2; // initialize number of intervals to 2 count = ; // initialize counter for iterations while(fabs(ans-prevans)>eps && count<itermax)//keep doubling no.of intervals // until convergence occurs or reach // max no. of iterations count++; // increase the iteration counter by 1 h = (b - a)/n; // set the stepsize prevans = ans; // set "previous answer" to that from // previous iteration ans = simp(f, a, b, n); // do Simpson s rule with n intervals if (n > 2) printf ("%13.5f %15.1f %15.1f %8.5f \n", h, ans, (ans-prevans), (ans-prevans)/(h*h*h*h)); else printf ("%13.5f %15.1f \n", h, ans); // print result for this iteratio n *= 2; // double n for next iteration if (count == ITERMAX) // check that convergence occurred and // print error message if it did not printf (" ERROR: Did not converge to the desired precision in %2d iterations The output is as follows. You can see that the error goes down like h 4 as expected. h ans ans-prevans (ans-prevans)/h^
5 Hence, the answer to 8 decimal places is The program stopped when the difference between the current answer and the previous answer (with half the number of intervals) is less than the desired accuracy of 1 8. This required n = (b a)/h = 128 intervals. Note: Although not a rigorous result, the last value is generally within the desired precision of the exact answer. This is certainly the case if the error is small enough that higher order terms beyond h 4 in the expansion of the error are negligible. 3. Romberg Integration I defined three separate functions, romb.c, which does the Romberg error extrapolation and which calls trap.c, and call romb.c which calls the Romberg routine. It is also necessary to define a variable ITER MAX which gives the maximum number Romberg iterations. In order that this variable can be accessed from both romb.c and call romb.c it is defined in a file romb.h which is included in romb.c and call romb.c. Here is romb.c /****************************************************************** * File: romb.c * * usage: romb(f, a, b, iter) * * where f(x) is the function to be integrated using * Romberg integration. * a is the lower limit. * b is the upper limit. * n is the number of intervals. * iter is the iteration level of the Romberg integration. * iter = is trapezium, iter = 1 is Simpson, etc. * To use: call romb repeatedly with iter =, 1, 2 etc. * Uses the trapezium rule function trap(f, a, b, n). * The value of ITERMAX is given in romb.h *****************************************************************/ #include <math.h> #include "romb.h" double romb (double f(double), double a, double b, int iter) double static R[ITERMAX][ITERMAX]; 5
6 double scale; double trap(); int i, n; n = pow(2, iter); // get the value of n R[][iter] = trap(f, a, b, n); // trapezium rule with n intervals scale = 4; for (i = 1; i <= iter; i++) // do Romberg iterations to level "iter" // for iter= (1st call) this loop is ignore R[i][iter] = (scale * R[i-1][iter] - R[i-1][iter-1]) / (scale - 1); scale *= 4; return R[iter][iter]; NotethattheRombergarrayR[][]isdeclaredstatic,sothatthevaluesinitarepreserved between successive calls to the function romb. This is essential because romb will be called successivelywithiterequalto,1,2,,andeachvalueof iterneedsvaluesofthematrix R obtained from previous values of iter in order to do the Romberg error elimination. Hence, these must be preserved between successive calls. Note, too, that there is a small inefficiency in this code. When evaluating the trapezium rule for 2n intervals half the function evaluations have already been done in the calculation for n intervals, and an efficient code would incorporate the result for n intervals to avoid calculating those function values again. However, here, for simplicity, I just call the routine trap for each value of n, thereby recalculating previously calculated values. The file romb.h just contains the one line #define ITER_MAX 1 Next here is call romb.c: /****************************************************************** * The value of ITERMAX is given in romb.h ******************************************************************/ #include <math.h> #include <stdio.h> #include "romb.h" double f(double x) return exp(-x*x/2); // define function to be integrated main() 6
7 double x, a, b, ans, prevans, EPS; double romb(); int i, iter ; b = 1.; a = ; EPS = 1.e-12; ans = 1.e+1; // set upper limit // set lower limit // set desired precision // initially set "answer" to a // ridiculously large value prevans = ; printf (" iter ans ans - prevans \n");//print header iter = ; while(fabs(ans-prevans)>eps && iter<=itermax)//keep doubling no.of intervals // until convergence occurs or reach // max no. of iterations prevans = ans; // set "previous answer" to that from // previous iteration ans = romb(f, a, b, iter); // call Romberg at level "iter" if (iter > ) printf ("%5i %18.13f %13.4e \n", iter, ans, fabs(ans-prevans)) else printf ("%5i %18.13f\n",iter,ans);//print result for this iteration iter++; // increase the iteration level by 1 if (iter > ITERMAX) // check that convergence occurred and // print error message if it did not printf (" ERROR:Did not converge to the desired precision, %9.4e, in %2d ite else printf("\n Ans =%18.13f\n", ans); (trap.c has already been given above). The code is compiled with the command gcc trap.c romb.c call_romb.c The output is as follows: iter ans ans - prevans e e e e e-13 Ans =
8 The program stopped when (answer - previous answer) is less than The answer is therefore Note the rapid convergence. 4. Consider one interval, i.e. I = x1 x f(x)dx where x 1 x = h. Expanding f(x) about x 1/2 gives f(x) = f 1/2 +(x x 1/2 )f 1/2 +(x x 1/2 ) 21 2 f 1/2 +. Integrating from x to x 1 the term involving f 1/2 gives zero and so we have I = hf 1/ f 1/2 3 [ (x x1/2 ) 3] x 1 x + = hf 1/2 + h3 24 f 1/2 +. To leading order in h we can write f 1/2 = (f 1 f )/h and so our final result for one interval is I = hf 1/2 + h2 24 (f 1 f )+. Now consider the integral from x (= a) to x n (= b) and divide the range of integration into n intervals. This gives b a f(x)dx = h(f 1/2 +f 3/2 + +f n 1/2 )+ h2 [ ] f 24 1 f +f 2 f 1 + +f n f n 1 + = h(f 1/2 +f 3/2 + +f n 3/2 +f n 1/2 )+ h2 24 [f (b) f (a)]+. Hence the midpoint rule, like the trapezium rule, is a second order method, i.e. the error is proportional to h Oscillations of a pendulum (a) The energy of a pendulum, given by E = 1 2 ml θ 2 +mgl(1 cosθ), is conserved. Since θ = when θ = θ m, the energy is given by E = mgl(1 cosθ m ). Hence [ ] 1/2 2g θ = l (cosθ cosθ m) = 2π 2 cosθ cosθm. T where T = 2π l/g is the period for small oscillations. The time for the pendulum to swing from θ = to θ m is a quarter of a period and so T(θ m ) T = 2 π θm dθ cosθ cosθm. 8
9 (b) Now cosθ = 1 2sin 2 θ/2 so T(θ m ) T = 1 π θm dθ sin 2 (θ m /2) sin 2 (θ/2) Let sinψ = sin(θ/2)/sin(θ m /2) so (1/2)cos(θ/2)dθ = sin(θ m /2) cosψdψ. Hence we have T(θ m ) T = 1 π = 2 π = 2 π 2cosψ sin(θ m /2)dψ cos(θ/2) sin(θ m /2) 1 sin 2 ψ dψ cos(θ/2) dψ 1 sin 2 (θ m /2)sin 2 ψ. (c) Use the Taylor series expansion 1 1 x 2 = x x4 + to obtain T(θ m ) T = 2 π [ sin2 (θ m /2)sin 2 ψ + 3 ] 8 sin4 (θ m /2)sin 4 ψ + dψ. Now dψ = π 2, sin 2 ψdψ = 1 2 sin 4 ψdψ = 1 4 = 1 4 (1 cos2ψ)dψ = π 4, (1 2cos2ψ +cos 2 2ψ)dψ [1 2cos2ψ + 12 ] (1+cos4ψ) dψ = 3π 16. This gives T(θ m ) T = sin2 ( θm 2 ) sin4 ( θm 2 ) +, i.e. a = 1/4,b = 9/64. (d) Now we do the numerics. I chose to use Simpson s rule, and use the file simp.c described above for this. I call simp.c with the following code, which I call pend.c: 9
10 #include <math.h> #include <stdio.h> #define PI // Numerical value of Pi / 2 double theta_m; // By declaring theta_m outside any of the // functions it is global in scope double f(double x) // define function to be integrated return 1 / sqrt(1 - pow(sin(x),2) * pow(sin(.5*theta_m),2)); main() double f(double), x, h, a, b, ans, ansold, eps); double simp(); int i, n; eps = 1.E-6; ans = ; ansold = 1.E+4; a = ; b = PI2; printf (" theta_m = "); scanf ("%lf", &theta_m); // set the precision; 1^-6 here // set lower limit // set upper limit // prompt for theta_max // give the value of theta_max printf (" h ans ans-prev ans \n"); n = 2; while (fabs(ansold - ans) > eps) // keep doubling no. of intervals until // desired precision has been obtained h = (b - a) / n; ansold = ans; ans = simp(f, a, b, n); ans /= PI2; // divide by PI2 if (n > 2) printf ("%12.5f %12.6f %13.4e\n", h, ans, fabs(ans-ansold)); else printf ("%12.5f %12.6f \n", h, ans); n *= 2; // double n for next iteration NotethatIreadinthevalueofθ m fromthecommandline,soidonotneedtorecompile for different values of this parameter. Study the form of the scanf command (the & symbol means the variable is passed by reference ). Note, too, that I declared theta m before any of the functions, so it is global in scope, i.e. it is accessible to all the routines. If I had not done this, the function f(x) would 1
11 not have known its value, and incorrect results would have occurred. A classier way to do this would be to put the declaration for theta m, and the definition of PI2, in a file called, say pend.h, and add the statement #include "pend.h" near the top of pend.c before any functions are defined. Running the code produces the output shown below. Columns of output refer to h, answer, and answer - previous answer. The program stops when the last column is less than 1 6. The results are compared with the values from the series (up to order θ 4 m). As expected the series works well for small θ m but is poor for larger values. Notice that the period is close to that for small oscillations up to fairly large values of θ m. For example, with θ m = π/4, the difference is only about 4%. OUTPUT theta_m =.1 h ans ans-prev ans e-8 Period = 1.63 Series -> 1.63 theta_m =.2 h ans ans-prev ans e e-12 Period = Series -> theta_m = (= pi/4) h ans ans-prev ans e e-7 Period = Series -> theta_m = (= pi/2) h ans ans-prev ans e e e-7 Period = Series ->
12 theta_m = (= 3pi/4) h ans ans-prev ans e e e e-7 Period = Series -> First of all we do the substitution x = y 2 so the singularity at the lower limit is removed: I = 1 sinx dx = 2 x3/2 1 siny 2 y 2 dy. (1) We can t use the trapezium rule because this would require evaluation of the integrand at y = which is ill defined. Hence use the Midpoint Rule. I put the midpoint routine in a separate file, midpt.c, as follows: /****************************************************************** * File: midpt.c * * usage: midpt(f, a, b, n) * * where f(x) is the the function to be integrated using the * midpoint rule * a is the lower limit * b is the upper limit * n is the number of intervals * To use: repeatedly call the routine, doubling n each time until * the desired accuracy has been reached. *****************************************************************/ double midpt (double f(double), double a, double b, int n) double h, sum; int i; h = (b - a) / n; // set stepsize sum = ; // initialize for (i = ; i < n; i++) sum += f(a + (i+.5)*h); // do the sum return h * sum; // return answer and call this function with the following routine: 12
13 #include <math.h> #include <stdio.h> double f(double x) return 2 * sin(x*x) / (x*x); // define function to be integrated main() double x, a, b, h, ans, prevans, eps; double midpt(); int i, n, iter; eps = 1.e-4; ans = ; prevans = 1e+1; b = 1.; a = ; // set the precision; 1^-4 here // set upper limit // set lower limit printf (" h ans ans-prev ans \n"); n = 1; while (fabs(prevans - ans) > eps) //keep doubling no. of intervals until // desired precision has been obtained prevans = ans; h = (b - a) / n; // set width of one interval ans = midpt(f, a, b, n); // call midpoint method if (n > 1) printf ("%13.5f %13.8f %13.4e\n", h, ans, fabs(ans-prevans)); else printf ("%13.5f %13.8f \n", h, ans); // print result n *= 2; // double n for next iteration The resulting output is h ans ans-prev ans e e e e e e-5 The program stopped when the difference between the last two estimates is less than 1 4. The answer to 4 dps is therefore
14 7. [242 students only] (a) First of all we evaluate the integrals I m = e x2 x m dx for m =,2,4 and 6. The result for m = is given to you in the question: I = π. To get I 2 we integrate by parts: I 2 = e x2 x 2 dx = 1 x d 2 = 1 [ xe x2] 2 dx e x2 dx e x2 dx = I 2 = π 2. Integrating by parts in the same way gives I 4 = 3 2 I 2 = 3 π 4 I 6 = 5 2 I 4 = 15 π 8 The source code below generates the x i and w i from a numerical recipes program. It gives the same results as cutting and pasting the values from the table I gave. SOURCE IMPLICIT REAL(8), REAL(8) INTEGER NONE DIMENSION(5) :: x, w sqrtpi, x2, x4, x6 N, i sqrtpi = sqrt(acos(-1._8)) print (A, $), " N = " read *, N if (N == 4) then x(1) = x(2) = x(3) = x(4) = w(1) = w(2) =
15 w(3) = w(4) = elseif (N == 3) then x(1) = x(2) =. x(3) = w(1) = w(2) = w(3) = elseif (N == 2) then x(1) = x(2) = w(1) = w(2) = else print (" N must be 2, 3 or 4") stop endif END x2 = ; x4 = ; x6 = do i = 1, N x2 = x2 + x(i)**2 * w(i) x4 = x4 + x(i)**4 * w(i) x6 = x6 + x(i)**6 * w(i) enddo print (i2,2x,8f1.6), N, x2, sqrtpi/2, x4, 3*sqrtpi/4, x6, 15*sqrtpi/8 The output below shows results for integrals of f(x) = x 2,x 4,x 6 and x 8 together with the exact results derived above. OUTPUT (Running the program 3 times, just displaying the important line of output, and adding a first line to label the columns.) N x2 x2(ex) x4 x4(ex) x6 x6(ex) It is seen that i. with N = 2 the exact answer is given for x 2 but not for x 4 or x 6, ii. with N = 3 the exact answer is given for x 2 and x 4 but not for x 6, and iii. with N = 4 the exact answer is given for x 2,x 4 and x 6, as requested. Bearing in mind that the method gives correctly the trivial result of for f(x) = x m with m odd, we see that these results are consistent with the claim that the method works exactly for polynomials up to order 2N 1. 15
16 (b) The source code is REAL(8), DIMENSION(4) :: x, w REAL(8) sum f(x) = 1/(exp(x) + 1) x(1) = x(2) = x(3) = x(4) = w(1) = w(2) = w(3) = w(4) = sum = do i = 1, 4 sum = sum + w(i) * f(x(i)) enddo print (" Integral = ", f12.5), sum END The output is Integral = so the answer is.88623, which is, in fact, correct to 5 decimal places. In fact, the integral turns out to equal π/2, the same as x2 exp( x 2 )dx in part (a) (a fact which I had not realized when I set the question.) 16
Queens College, CUNY, Department of Computer Science Numerical Methods CSCI 361 / 761 Fall 2018 Instructor: Dr. Sateesh Mane
Queens College, CUNY, Department of Computer Science Numerical Methods CSCI 36 / 76 Fall 28 Instructor: Dr. Sateesh Mane c Sateesh R. Mane 28 6 Homework lecture 6: numerical integration If you write the
More informationExercises C-Programming
Exercises C-Programming Claude Fuhrer (claude.fuhrer@bfh.ch) 0 November 016 Contents 1 Serie 1 1 Min function.................................. Triangle surface 1............................... 3 Triangle
More informationAn interesting related problem is Buffon s Needle which was first proposed in the mid-1700 s.
Using Monte Carlo to Estimate π using Buffon s Needle Problem An interesting related problem is Buffon s Needle which was first proposed in the mid-1700 s. Here s the problem (in a simplified form). Suppose
More informationCSE 251 PROJECT 1. Andrew Christlieb. Monday Class AND Friday Class Abstract. Web:
CSE 51 PROJECT 1 Andrew Christlieb Monday Class 0-03-14 AND Friday Class 01-31-14 Abstract Web: http://www.cse.msu.edu/ cse51 Project 1 due date: (Monday Class) 0-17-14 AND (Friday Class)0-14-14, time:
More informationnag 1d quad gauss 1 (d01tac)
1. Purpose nag 1d quad gauss 1 () nag 1d quad gauss 1 () computes an estimate of the definite integral of a function of known analytical form, using a Gaussian quadrature formula with a specified number
More informationMAT137 Calculus! Lecture 31
MAT137 Calculus! Lecture 31 Today: Next: Integration Methods: Integration Methods: Trig. Functions (v. 9.10-9.12) Rational Functions Trig. Substitution (v. 9.13-9.15) (v. 9.16-9.17) Integration by Parts
More informationnag 1d quad gauss (d01bac)
1. Purpose nag 1d quad gauss () nag 1d quad gauss () computes an estimate of the definite integral of a function of known analytical form, using a Gaussian quadrature formula with a specified number of
More informationSYDE 312 UNIT 4: EXTRA QUADRATURE PROBLEMS
SYDE 3 UNIT 4: EXTRA QUADRATURE PROBLEMS Problem E x x + Use f(x) = /x x + You can t use the Matlab gaussquad file in the provided form, because it implements composite Gauss-Legendre quadrature with multiple
More informationThe Newton Method as a Short WEB Example
The Newton Method as a Short WEB Example August 31, 1996 15:22 Abstract: This is written in John Krommes FWEB but with the output higher level language being C. FWEB is the most supported of the dialects
More informationLECTURE 0: Introduction and Background
1 LECTURE 0: Introduction and Background September 10, 2012 1 Computational science The role of computational science has become increasingly significant during the last few decades. It has become the
More informationIntroduction to C++ Introduction to C++ Week 6 Dr Alex Martin 2013 Slide 1
Introduction to C++ Introduction to C++ Week 6 Dr Alex Martin 2013 Slide 1 Numerical Integration Methods The Trapezoidal Rule If one has an arbitrary function f(x) to be integrated over the region [a,b]
More informationApplied Programming and Computer Science, DD2325/appcs15 PODF, Programmering och datalogi för fysiker, DA7011
Applied Programming and Computer Science, DD2325/appcs15 PODF, Programmering och datalogi för fysiker, DA7011 Autumn 2015 Lecture 3, Simple C programming M. Eriksson (with contributions from A. Maki and
More informationExercises for a Numerical Methods Course
Exercises for a Numerical Methods Course Brian Heinold Department of Mathematics and Computer Science Mount St. Mary s University November 18, 2017 1 / 73 About the class Mix of Math and CS students, mostly
More informationCarleton University Department of Systems and Computer Engineering SYSC Foundations of Imperative Programming - Winter 2012
Carleton University Department of Systems and Computer Engineering SYSC 2006 - Foundations of Imperative Programming - Winter 2012 Lab 2 - C Functions Objective The objective of this lab is to write some
More informationComputer Simulations
Computer Simulations A practical approach to simulation Semra Gündüç gunduc@ankara.edu.tr Ankara University Faculty of Engineering, Department of Computer Engineering 2014-2015 Spring Term Ankara University
More informationContents. Hilary Term. Summary of Numerical Analysis for this term. Sources of error in numerical calculation. Solving Problems
Contents Hilary Term 1 Root Finding 4 11 Bracketing and Bisection 5 111 Finding the root numerically 5 112 Pseudo BRACKET code 7 113 Drawbacks 8 114 Tips for success with Bracketing & Bisection 9 115 Virtues
More information1.00 Lecture 32. Integration. Reading for next time: Numerical Recipes Packaging Functions in Objects
1.00 Lecture 32 Integration Reading for next time: Numerical Recipes 347-368 Packaging Functions in Objects Consider writing a method that evaluates, integrates or finds the roots of a function: Evaluate:
More information(Refer Slide Time: 02:59)
Numerical Methods and Programming P. B. Sunil Kumar Department of Physics Indian Institute of Technology, Madras Lecture - 7 Error propagation and stability Last class we discussed about the representation
More informationQuestions Q1. (a) Find the values of the constants A, B and C. (4) b) Hence find
Questions Q1. (a) Find the values of the constants A, B and C. (4) b) Hence find (ii) Find, leaving your answer in the form a + ln b, where a and b are constants. (6) (Total 10 marks) Q2. (a) Find the
More information2nd Year Computational Physics Week 3 (standard): Numerical calculus
nd Year Computational Physics Week 3 (standard): Numerical calculus Last compiled September 8, 017 1 Contents 1 Introduction 4 Prelab Questions 4 3 Numerical Differentiation 7 3.1 Background...............................
More informationMIDTERM. Section: Signature:
MIDTERM Math 32B 8/8/2 Name: Section: Signature: Read all of the following information before starting the exam: Check your exam to make sure all pages are present. NO CALCULATORS! Show all work, clearly
More information2. Numbers In, Numbers Out
COMP1917: Computing 1 2. Numbers In, Numbers Out Reading: Moffat, Chapter 2. COMP1917 15s2 2. Numbers In, Numbers Out 1 The Art of Programming Think about the problem Write down a proposed solution Break
More information2. Numbers In, Numbers Out
REGZ9280: Global Education Short Course - Engineering 2. Numbers In, Numbers Out Reading: Moffat, Chapter 2. REGZ9280 14s2 2. Numbers In, Numbers Out 1 The Art of Programming Think about the problem Write
More informationClasses of Real Numbers 1/2. The Real Line
Classes of Real Numbers All real numbers can be represented by a line: 1/2 π 1 0 1 2 3 4 real numbers The Real Line { integers rational numbers non-integral fractions irrational numbers Rational numbers
More informationPHYSICS 115/242 Homework 5, Solutions X = and the mean and variance of X are N times the mean and variance of 12/N y, so
PHYSICS 5/242 Homework 5, Solutions. Central limit theorem. (a) Let y i = x i /2. The distribution of y i is equal to for /2 y /2 and zero otherwise. Hence We consider µ y y i = /2 /2 σ 2 y y 2 i y i 2
More informationFrom: Robert Sharpley Subject: Homeworks #6 Date: February 22, :09:53 AM EST Cc: Robert Sharpley
From: Robert Sharpley Subject: Homeworks #6 Date: February 22, 2006 9:09:53 AM EST Cc: Robert Sharpley %% Homework #5 - Solutions %% Here is a matlab code
More informationRaspberry Pi Basics. CSInParallel Project
Raspberry Pi Basics CSInParallel Project Sep 11, 2016 CONTENTS 1 Getting started with the Raspberry Pi 1 2 A simple parallel program 3 3 Running Loops in parallel 7 4 When loops have dependencies 11 5
More informationComputers in Engineering Root Finding Michael A. Hawker
Computers in Engineering COMP 208 Root Finding Michael A. Hawker Root Finding Many applications involve finding the roots of a function f(x). That is, we want to find a value or values for x such that
More informationAn Introduction to C Through Annotated Examples
An Introduction to C Through Annotated Examples by Henry M. Walker Grinnell College, Grinnell, IA c 1998 by Henry M. Walker Permission to make digital or hard copies of all or part of this work for personal
More information16.216: ECE Application Programming Fall 2011
16.216: ECE Application Programming Fall 2011 Exam 2 Solution 1. (24 points, 6 points per part) Multiple choice For each of the multiple choice questions below, clearly indicate your response by circling
More informationFunctions. Systems Programming Concepts
Functions Systems Programming Concepts Functions Simple Function Example Function Prototype and Declaration Math Library Functions Function Definition Header Files Random Number Generator Call by Value
More informationCpSc 111 Lab 5 Conditional Statements, Loops, the Math Library, and Redirecting Input
CpSc Lab 5 Conditional Statements, Loops, the Math Library, and Redirecting Input Overview For this lab, you will use: one or more of the conditional statements explained below scanf() or fscanf() to read
More informationWhat Secret the Bisection Method Hides? by Namir Clement Shammas
What Secret the Bisection Method Hides? 1 What Secret the Bisection Method Hides? by Namir Clement Shammas Introduction Over the past few years I have modified the simple root-seeking Bisection Method
More informationand F is an antiderivative of f
THE EVALUATION OF DEFINITE INTEGRALS Prepared by Ingrid Stewart, Ph.D., College of Southern Nevada Please Send Questions Comments to ingrid.stewart@csn.edu. Thank you! We have finally reached a point,
More informationMath 2374 Spring 2007 Midterm 3 Solutions - Page 1 of 6 April 25, 2007
Math 374 Spring 7 Midterm 3 Solutions - Page of 6 April 5, 7. (3 points) Consider the surface parametrized by (x, y, z) Φ(x, y) (x, y,4 (x +y )) between the planes z and z 3. (i) (5 points) Set up the
More informationMath 250A (Fall 2009) - Lab I: Estimate Integrals Numerically with Matlab. Due Date: Monday, September 21, INSTRUCTIONS
Math 250A (Fall 2009) - Lab I: Estimate Integrals Numerically with Matlab Due Date: Monday, September 21, 2009 4:30 PM 1. INSTRUCTIONS The primary purpose of this lab is to understand how go about numerically
More informationAN OVERVIEW OF C, PART 3. CSE 130: Introduction to Programming in C Stony Brook University
AN OVERVIEW OF C, PART 3 CSE 130: Introduction to Programming in C Stony Brook University FANCIER OUTPUT FORMATTING Recall that you can insert a text field width value into a printf() format specifier:
More informationLecture 05 I/O statements Printf, Scanf Simple statements, Compound statements
Programming, Data Structures and Algorithms Prof. Shankar Balachandran Department of Computer Science and Engineering Indian Institute of Technology, Madras Lecture 05 I/O statements Printf, Scanf Simple
More informationNAG Library Routine Document D01BAF.1
NAG Library Routine Document Note: before using this routine, please read the Users Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent
More informationThe diagram above shows a sketch of the curve C with parametric equations
1. The diagram above shows a sketch of the curve C with parametric equations x = 5t 4, y = t(9 t ) The curve C cuts the x-axis at the points A and B. (a) Find the x-coordinate at the point A and the x-coordinate
More informationmain() { double gm; gm = (sqrt((double)5) - 1)/2; printf (" The Golden Mean is %11.8f \n", gm); } OUTPUT The Golden Mean is 0.
PHYSICS 115/242 Homework 1, Solutions 1. (a) SOURCE CODE printf (" Hello World \n"); ----------- Hello World (b) i. SOURCE CODE double x; x = 1.9e10; printf (" %11.1e \n", x); ----------- 1.9e+10 ii. SOURCE
More information5.5 Newton s Approximation Method
498CHAPTER 5. USING DERIVATIVES TO ANALYZE FUNCTIONS; FURTHER APPLICATIONS 4 3 y = x 4 3 f(x) = x cosx y = cosx 3 3 x = cosx x cosx = 0 Figure 5.: Figure showing the existence of a solution of x = cos
More informationMATH 417 Homework 8 Instructor: D. Cabrera Due August 4. e i(2z) (z 2 +1) 2 C R. z 1 C 1. 2 (z 2 + 1) dz 2. φ(z) = ei(2z) (z i) 2
MATH 47 Homework 8 Instructor: D. abrera Due August 4. ompute the improper integral cos x (x + ) dx Solution: To evaluate the integral consider the complex integral e i(z) (z + ) dz where is the union
More informationCpSc 1011 Lab 4 Formatting and Flow Control Windchill Temps
CpSc 1011 Lab 4 Formatting and Flow Control Windchill Temps Overview By the end of the lab, you will be able to: use fscanf() to accept inputs from the user and use fprint() for print statements to the
More informationECE15: Homework 10. void wordstats(file *fp, char string[]) { void printfrequencies(file *fp) {
ECE15: Homework 10 Recall that in the Unix dialogues shown below, we denote the prompt by ( )$ and show user input in red and computer output in black. We indicate a single space by in computer output,
More information#3. (Recursion) Write a recursive function to compute f(x) = f(x - 1) + f(x - 2) with f(0) = 0 and f(1) = 1.
EGN 3210 Sample Test 2 Dr. Fernando Gonzalez NAME S.S.# #1. (Functions) Write a function that receives 3 integers, and returns the value of the largest one through the function name. #2. (Functions) What
More informationMachine Computation of the Sine Function
Machine Computation of the Sine Function Chuck Allison CNS 3320 Numerical Software Engineering Utah Valley State College February 2007 Abstract This note shows how to determine the number of terms to use
More information= f (a, b) + (hf x + kf y ) (a,b) +
Chapter 14 Multiple Integrals 1 Double Integrals, Iterated Integrals, Cross-sections 2 Double Integrals over more general regions, Definition, Evaluation of Double Integrals, Properties of Double Integrals
More informationMATLAB Lecture 4. Programming in MATLAB
MATLAB Lecture 4. Programming in MATLAB In this lecture we will see how to write scripts and functions. Scripts are sequences of MATLAB statements stored in a file. Using conditional statements (if-then-else)
More informationVariables are used to store data (numbers, letters, etc) in MATLAB. There are a few rules that must be followed when creating variables in MATLAB:
Contents VARIABLES... 1 Storing Numerical Data... 2 Limits on Numerical Data... 6 Storing Character Strings... 8 Logical Variables... 9 MATLAB S BUILT-IN VARIABLES AND FUNCTIONS... 9 GETTING HELP IN MATLAB...
More informationIntroduction to Computer Programming with MATLAB Calculation and Programming Errors. Selis Önel, PhD
Introduction to Computer Programming with MATLAB Calculation and Programming Errors Selis Önel, PhD Today you will learn Numbers, Significant figures Error analysis Absolute error Relative error Chopping
More informationFinal Exam May 2, 2017
Math 07 Calculus II Name: Final Exam May, 07 Circle the name of your instructor and, in the appropriate column, the name of your recitation leader. The second row is the time of your lecture. Radu Ledder
More informationLesson #3. Variables, Operators, and Expressions. 3. Variables, Operators and Expressions - Copyright Denis Hamelin - Ryerson University
Lesson #3 Variables, Operators, and Expressions Variables We already know the three main types of variables in C: int, char, and double. There is also the float type which is similar to double with only
More information1 Programs for double integrals
> restart; Double Integrals IMPORTANT: This worksheet depends on some programs we have written in Maple. You have to execute these first. Click on the + in the box below, then follow the directions you
More informationScope of Variables. In general, it is not a good practice to define many global variables. 1. Use global to declare x as a global variable.
Scope of Variables The variables used in function m-files are known as local variables. Any variable defined within the function exists only for the function to use. The only way a function can communicate
More informationIntroduction to C Language
Introduction to C Language Instructor: Professor I. Charles Ume ME 6405 Introduction to Mechatronics Fall 2006 Instructor: Professor Charles Ume Introduction to C Language History of C Language In 1972,
More informationEuler s Methods (a family of Runge- Ku9a methods)
Euler s Methods (a family of Runge- Ku9a methods) ODE IVP An Ordinary Differential Equation (ODE) is an equation that contains a function having one independent variable: The equation is coupled with an
More information1.00 Lecture 19. Packaging Functions in Objects
1.00 Lecture 19 Numerical Methods: Root Finding Packaging Functions in Objects Consider writing method that finds root of function or evaluates a function, e.g., f(x)= 0 on some interval [a, b], or find
More informationMath 126 Winter CHECK that your exam contains 8 problems.
Math 126 Winter 2016 Your Name Your Signature Student ID # Quiz Section Professor s Name TA s Name CHECK that your exam contains 8 problems. This exam is closed book. You may use one 8 1 11 sheet of hand-written
More informationTechnical Questions. Q 1) What are the key features in C programming language?
Technical Questions Q 1) What are the key features in C programming language? Portability Platform independent language. Modularity Possibility to break down large programs into small modules. Flexibility
More informationThere are also formulas of higher order for this situation, but we will refrain from giving them.
136 Chapter 4. Integration of Functions N = 1 2 3 4 (total after N = 4) Figure 4.2.1. Sequential calls to the routine trapzd incorporate the information from previous calls and evaluate the integrand only
More informationC introduction: part 1
What is C? C is a compiled language that gives the programmer maximum control and efficiency 1. 1 https://computer.howstuffworks.com/c1.htm 2 / 26 3 / 26 Outline Basic file structure Main function Compilation
More informationChapter 1. Numeric Artifacts. 1.1 Introduction
Chapter 1 Numeric Artifacts 1.1 Introduction Virtually all solutions to problems in electromagnetics require the use of a computer. Even when an analytic or closed form solution is available which is nominally
More informationStructured Programming. Dr. Mohamed Khedr Lecture 4
Structured Programming Dr. Mohamed Khedr http://webmail.aast.edu/~khedr 1 Scientific Notation for floats 2.7E4 means 2.7 x 10 4 = 2.7000 = 27000.0 2.7E-4 means 2.7 x 10-4 = 0002.7 = 0.00027 2 Output Formatting
More informationExact real arithmetic. Keith Briggs
Exact real arithmetic Keith Briggs Keith.Briggs@bt.com more.btexact.com/people/briggsk2/xr.html 2002 Nov 20 15:00 Typeset in L A T E X2e on a linux system Exact real arithmetic p.1/35 Complexity Outline
More informationLESSON 5 FUNDAMENTAL DATA TYPES. char short int long unsigned char unsigned short unsigned unsigned long
LESSON 5 ARITHMETIC DATA PROCESSING The arithmetic data types are the fundamental data types of the C language. They are called "arithmetic" because operations such as addition and multiplication can be
More informationC Functions. CS 2060 Week 4. Prof. Jonathan Ventura
CS 2060 Week 4 1 Modularizing Programs Modularizing programs in C Writing custom functions Header files 2 Function Call Stack The function call stack Stack frames 3 Pass-by-value Pass-by-value and pass-by-reference
More informationNAG Library Function Document nag_quad_2d_fin (d01dac)
d1 Quadrature d1dac NAG Library Function Document nag_quad_2d_fin (d1dac) 1 Purpose nag_quad_2d_fin (d1dac) attempts to evaluate a double integral to a specified absolute accuracy by repeated applications
More informationStudy Guide for Test 2
Study Guide for Test Math 6: Calculus October, 7. Overview Non-graphing calculators will be allowed. You will need to know the following:. Set Pieces 9 4.. Trigonometric Substitutions (Section 7.).. Partial
More informationRectangle Sums
Rectangle Sums --208 You can approximate the area under a curve using rectangles. To do this, divide the base interval into pieces subintervals). Then on each subinterval, build a rectangle that goes up
More informationCalculus I Review Handout 1.3 Introduction to Calculus - Limits. by Kevin M. Chevalier
Calculus I Review Handout 1.3 Introduction to Calculus - Limits by Kevin M. Chevalier We are now going to dive into Calculus I as we take a look at the it process. While precalculus covered more static
More informationPhysics 306 Computing Lab 5: A Little Bit of This, A Little Bit of That
Physics 306 Computing Lab 5: A Little Bit of This, A Little Bit of That 1. Introduction You have seen situations in which the way numbers are stored in a computer affects a program. For example, in the
More information2.9 Linear Approximations and Differentials
2.9 Linear Approximations and Differentials 2.9.1 Linear Approximation Consider the following graph, Recall that this is the tangent line at x = a. We had the following definition, f (a) = lim x a f(x)
More informationLecture 5. Functions II. Functions with Arguments. CptS 121 Summer 2016 Armen Abnousi
Lecture 5 Functions II Functions with Arguments CptS 121 Summer 2016 Armen Abnousi Remember Functions break problems into smaller pieces Easier to read, test and maintain Functions allow to avoid repetition
More informationModule 10A Lecture - 20 What is a function? Why use functions Example: power (base, n)
Programming, Data Structures and Algorithms Prof. Shankar Balachandran Department of Computer Science and Engineering Indian Institute of Technology, Madras Module 10A Lecture - 20 What is a function?
More information1. The keyword main in C language is used for
1. The keyword main in C language is used for a. an user defined function *b. the first function to be executed in the program c. an user defined variable 2. The role of a C compiler is to translate a.
More informationControl Structure: Loop
Control Structure: Loop Knowledge: Understand the various concepts of loop control structure Skill: Be able to develop a program involving loop control structure 1 Loop Structure Condition is tested first
More information1.00 Lecture 25. Root Finding
1.00 Lecture 25 Numerical Methods: Root Finding Reading for next time: Big Java: section 19.4 Root Finding Two cases: One dimensional function: f(x)= 0 Systems of equations (F(X)= 0), where X and 0 are
More informationPartial Derivatives (Online)
7in x 10in Felder c04_online.tex V3 - January 21, 2015 9:44 A.M. Page 1 CHAPTER 4 Partial Derivatives (Online) 4.7 Tangent Plane Approximations and Power Series It is often helpful to use a linear approximation
More informationFunctions. Autumn Semester 2009 Programming and Data Structure 1. Courtsey: University of Pittsburgh-CSD-Khalifa
Functions Autumn Semester 2009 Programming and Data Structure 1 Courtsey: University of Pittsburgh-CSD-Khalifa Introduction Function A self-contained program segment that carries out some specific, well-defined
More informationLecture 3. Review. CS 141 Lecture 3 By Ziad Kobti -Control Structures Examples -Built-in functions. Conditions: Loops: if( ) / else switch
Lecture 3 CS 141 Lecture 3 By Ziad Kobti -Control Structures Examples -Built-in functions Review Conditions: if( ) / else switch Loops: for( ) do...while( ) while( )... 1 Examples Display the first 10
More informationEngineering 12 - Spring, 1999
Engineering 12 - Spring, 1999 1. (18 points) A portion of a C program is given below. Fill in the missing code to calculate and display a table of n vs n 3, as shown below: 1 1 2 8 3 27 4 64 5 125 6 216
More informationPolar Coordinates. Calculus 2 Lia Vas. If P = (x, y) is a point in the xy-plane and O denotes the origin, let
Calculus Lia Vas Polar Coordinates If P = (x, y) is a point in the xy-plane and O denotes the origin, let r denote the distance from the origin O to the point P = (x, y). Thus, x + y = r ; θ be the angle
More information0.1 Numerical Integration Rules Using Maple
> restart; Numerical Integration Note: While reading this worksheet make sure that you re-execute each command by placing the cursor on the command line and pressing Enter. You should do this with every
More informationPresented, and Compiled, By. Bryan Grant. Jessie Ross
P a g e 1 Presented, and Compiled, By Bryan Grant Jessie Ross August 3 rd, 2016 P a g e 2 Day 1 Discovering Polar Graphs Days 1 & 2 Adapted from Nancy Stephenson - Clements High School, Sugar Land, Texas
More informationA Simple Fortran Primer
A Simple Fortran Primer 2nd Edition Rosemary Mardling and Daniel Price School of Physics & Astronomy Monash University 2016 1 Contents 1 Introduction 2 2 Simple Mathematical Expressions 3 3 Real and Integer
More informationNumerical Integration
Numerical Integration Numerical Integration is the process of computing the value of a definite integral, when the values of the integrand function, are given at some tabular points. As in the case of
More informationComputer Science & Engineering 150A Problem Solving Using Computers
Computer Science & Engineering 150A Problem Solving Using Computers Lecture 03 - Stephen Scott (Adapted from Christopher M. Bourke) 1 / 41 Fall 2009 Chapter 3 3.1 Building Programs from Existing Information
More informationSantiago AP Calculus AB/BC Summer Assignment 2018 AB: complete problems 1 64, BC: complete problems 1 73
Santiago AP Calculus AB/BC Summer Assignment 2018 AB: complete problems 1 64, BC: complete problems 1 73 AP Calculus is a rigorous college level math course. It will be necessary to do some preparatory
More informationASSIGNMENT BOOKLET. M.Sc.(Mathematics with Applications in Computer Science) Programming and Data Structures (1 st January, 2018 December, 2018)
ASSIGNMENT BOOKLET MMT-001 M.Sc.(Mathematics with Applications in Computer Science) Programming and Data Structures (1 st January, 2018 December, 2018) School of Sciences Indira Gandhi National Open University
More informationAnswer the following questions on the answer sheet that is provided. The computer must be switched off while you are busy with Section A.
UNIVERSITY OF THE FREE STATE DEPARTMENT OF COMPUTER SCIENCE AND INFORMATICS RIS 114 DATE: 25 April 2013 TIME: 180 minutes MARKS: 100 ASSESSORS: Prof. P.J. Blignaut & Mr. F. Radebe (+2 bonus marks) MODERATOR:
More informationThe following program computes a Calculus value, the "trapezoidal approximation of
Multicore machines and shared memory Multicore CPUs have more than one core processor that can execute instructions at the same time. The cores share main memory. In the next few activities, we will learn
More informationEC 413 Computer Organization
EC 413 Computer Organization C/C++ Language Review Prof. Michel A. Kinsy Programming Languages There are many programming languages available: Pascal, C, C++, Java, Ada, Perl and Python All of these languages
More information6-1 (Function). (Function) !*+!"#!, Function Description Example. natural logarithm of x (base e) rounds x to smallest integer not less than x
(Function) -1.1 Math Library Function!"#! $%&!'(#) preprocessor directive #include !*+!"#!, Function Description Example sqrt(x) square root of x sqrt(900.0) is 30.0 sqrt(9.0) is 3.0 exp(x) log(x)
More informationComputer Science & Engineering 150A Problem Solving Using Computers. Chapter 3. Existing Information. Notes. Notes. Notes. Lecture 03 - Functions
Computer Science & Engineering 150A Problem Solving Using Computers Lecture 03 - Functions Stephen Scott (Adapted from Christopher M. Bourke) Fall 2009 1 / 1 cbourke@cse.unl.edu Chapter 3 3.1 Building
More informationNumerical Integration
Numerical Integration 1 Functions using Functions functions as arguments of other functions the one-line if-else statement functions returning multiple values 2 Constructing Integration Rules with sympy
More informationHomework Set #2-3, Math 475B
Homework Set #2-3, Math 475B Part I: Matlab In the last semester you learned a number of essential features of MATLAB. 1. In this instance, you will learn to make 3D plots and contour plots of z = f(x,
More informationCOMP 208 Computers in Engineering
COMP 208 Computers in Engineering Lecture 14 Jun Wang School of Computer Science McGill University Fall 2007 COMP 208 - Lecture 14 1 Review: basics of C C is case sensitive 2 types of comments: /* */,
More informationFunctions in C. Lecture Topics. Lecture materials. Homework. Machine problem. Announcements. ECE 190 Lecture 16 March 9, 2011
Functions in C Lecture Topics Introduction to using functions in C Syntax Examples Memory allocation for variables Lecture materials Textbook 14.1-14.2, 12.5 Homework Machine problem MP3.2 due March 18,
More informationC Program. Output. Hi everyone. #include <stdio.h> main () { printf ( Hi everyone\n ); }
C Program Output #include main () { printf ( Hi everyone\n ); Hi everyone #include main () { printf ( Hi everyone\n ); #include and main are Keywords (or Reserved Words) Reserved Words
More information