Create a user-defined function \(f(x)\) that returns the value \(1+\frac{1}{2} \tanh 2 x\), then use a central difference to calculate the derivative of the function in the range \(-2 \leq x \leq 2\). Calculate an analytic formula for the derivative and make a graph with your numerical result and the analytic answer on the same plot. It may help to plot the exact answer as lines and the numerical one as dots. (Hint: In Python the tanh function is found in the math package, and it's called simply tanh.)

Short Answer

Expert verified
Define the function and import libraries. Use central difference to compute the numerical derivative, calculate the analytic derivative, and plot both results.

Step by step solution

01

Define the function

Define the user-defined function as specified. In Python, this can be easily done using a def statement.
02

Import necessary libraries

Import the math package to access the tanh function and other necessary packages like numpy for numerical computations and matplotlib for plotting.
03

Implement central difference

Using numpy, create an array of x values within the specified range -2 ≤ x ≤ 2. Then, utilize the central difference formula \(f'(x) ≈ \frac{f(x+h)-f(x-h)}{2h}\) for numerical differentiation.
04

Compute the analytic derivative

Calculate the derivative analytically by hand, knowing that the derivative of tanh(x) is \(1 - \tanh^2(x)\). The derivative of f(x) = 1 + 1/2 tanh(2x) can be found as f'(x) = 1/2 \cdot 2 (1 - \tanh^2(2x)) = (1 - \tanh^2(2x)).
05

Plot the results

Use matplotlib to plot both the numerical and analytical results. Plot the exact (analytical) answer as a line and the numerical one as dots.

Unlock Step-by-Step Solutions & Ace Your Exams!

  • Full Textbook Solutions

    Get detailed explanations and key concepts

  • Unlimited Al creation

    Al flashcards, explanations, exams and more...

  • Ads-free access

    To over 500 millions flashcards

  • Money-back guarantee

    We refund you if you fail your exam.

Over 30 million students worldwide already upgrade their learning with Vaia!

Key Concepts

These are the key concepts you need to understand to accurately answer the question.

Central Difference Method
The Central Difference Method is a numerical technique to approximate the derivative of a function. This method is very useful when you don't have the exact form of the derivative or when dealing with discretized data.
Here's how it works. Suppose you have a function \( f(x) \). The central difference method formula to approximate \( f'(x) \) is:
\[ f'(x) \approx \frac{f(x+h) - f(x-h)}{2h} \]
This formula gives us the slope of the function at a point \( x \) by looking at the points just to its left and right, separated by a small interval \( h \). The central difference method is more accurate than forward or backward difference methods because it takes into account the change in the function on both sides of \( x \).
To implement this in the Python programming language, we can use the numpy library for handling array operations efficiently. Here, \( h \) can be defined as a small value, like 0.01.
Analytic Derivative
The analytic derivative means determining the derivative of a function using calculus rather than numerical methods. For the function given in the exercise, \( f(x) = 1 + \frac{1}{2} \tanh(2x) \), we need to find its derivative analytically.
First, recall that the derivative of \( \tanh(x) \) is given by:
\[ \frac{d}{dx} \tanh(x) = 1 - \tanh^2(x) \]
Given the function \( f(x) \), its derivative can be computed step by step:
1. The derivative of \(1\) is \(0\).
2. The derivative of \( \frac{1}{2} \tanh(2x) \) requires the chain rule:
\[ \frac{d}{dx} \left( \frac{1}{2} \tanh(2x) \right) = \frac{1}{2} \cdot \frac{d}{dx} \tanh(2x) \cdot \frac{d}{dx} (2x) \]
3. Using the chain rule, we get:
\[ \frac{1}{2} \cdot (1 - \tanh^2(2x)) \cdot 2 = 1 - \tanh^2(2x) \]
Thus, the analytic derivative is:
\[ f'(x) = 1 - \tanh^2(2x) \]
This exact expression can be used to compare against the numerical approximation.
Python Programming
Python is a versatile programming language that is very useful for scientific computing. By utilizing libraries such as math, numpy, and matplotlib, you can perform complex numerical methods and visualize results effortlessly.
Here's a quick rundown to solve our problem in Python:
1. **Define the function**:
def f(x):
     return 1 + 1/2 * math.tanh(2 * x)
2. **Import necessary libraries**:
import math
import numpy as np
import matplotlib.pyplot as plt
3. **Central Difference Method**:
Create an array of x values using numpy:
x = np.linspace(-2, 2, 400)
Define h as a small step:
h = 0.01
Compute the numerical derivative:
numerical_derivative = (f(x + h) - f(x - h)) / (2 * h)
4. **Analytic Derivative**:
Using numpy for vectorized operations, define the exact derivative:
analytic_derivative = 1 - np.tanh(2 * x)**2
5. **Plot the Results**:
Use matplotlib to create the plot:
plt.plot(x, analytic_derivative, label='Analytic Derivative')
plt.scatter(x, numerical_derivative, label='Numerical Derivative', color='red', marker='o')
plt.legend()
plt.show()
This code will produce a graph comparing the numerical and analytical results, helping you visualize the accuracy of the Central Difference Method.

One App. One Place for Learning.

All the tools & learning materials you need for study success - in one app.

Get started for free

Most popular questions from this chapter

The diffraction limit of a telescope Our ability to resolve detail in astronomical observation is limited by the diffraction of light in our telescopes. Light from stars can be treated effectively as coming from a point source at infinity. When such light, with wavelength \(\lambda\), passes through the circular aperture of a telescope (which we'll assume to have unit radius) and is focused by the telescope in the focal plane, it produces not a single dot, but a circular diffraction pattern consisting of central spot surrounded by a series of concentric rings. The intensity of the light in this diffraction pattern is given by $$ I(r)=\left(\frac{J_{1}(k r)}{k r}\right)^{2} $$ where \(r\) is the distance in the focal plane from the center of the diffraction pattern, \(k=2 \pi / \lambda\), and \(J_{1}(x)\) is a Bessel function. The Bessel functions \(J_{m}(x)\) are given by $$ J_{m}(x)=\frac{1}{\pi} \int_{0}^{\pi} \cos (m \theta-x \sin \theta) \mathrm{d} \theta, $$ where \(m\) is a nonnegative integer and \(x \geq 0\). a) Write a Python function \(J(m, x)\) that calculates the value of \(J_{m}(x)\) using Simpson's rule with \(N=1000\) points. Use your function in a program to make a plot, on a single graph, of the Bessel functions \(J_{0}, J_{1}\) and \(J_{2}\) as a function of \(x\) from \(x=0\) to \(x=20\). b) Make a second program that makes a density plot of the intensity of the circular diffraction pattern of a point light source with \(\lambda=500 \mathrm{~nm}\), in a square region of the focal plane, using the formula given above. Your picture should cover values of \(r\) from zero up to about \(1 \mu \mathrm{m}\).

Gravitational pull of a uniform sheet A uniform square sheet of metal is floating motionless in space: The sheet is \(10 \mathrm{~m}\) on a side and of negligible thickness, and it has a mass of 10 metric tonnes. a) Consider the gravitational force due to the plate felt by a point mass of \(1 \mathrm{~kg}\) a distance \(z\) from the center of the square, in the direction perpendicular to the sheet, as shown above. Show that the component of the force along the \(z\)-axis is $$ F_{z}=G \sigma z \iint_{-L / 2}^{L / 2} \frac{\mathrm{d} x \mathrm{~d} y}{\left(x^{2}+y^{2}+z_{2}^{2}\right)^{3 / 2}}, $$ where \(G=6.674 \times 10^{-11} \mathrm{~m}^{3} \mathrm{~kg}^{-1} \mathrm{~s}^{-2}\) is Newton's gravitational constant and \(\sigma\) is the mass per unit area of the sheet. b) Write a program to calculate and plot the force as a function of \(z\) from \(z=0\) to \(z=10 \mathrm{~m}\). For the double integral use (double) Gaussian quadrature, as in Eq. (5.82), with 100 sample points along each axis. c) You should see a smooth curve, except at very small values of \(z\), where the force should drop off suddenly to zero. This drop is not a real effect, but an artifact of the way we have done the calculation. Explain briefly where this artifact comes from and suggest a strategy to remove it, or at least to decrease its size. This calculation can thought of as a model for the gravitational pull of a galaxy. Most of the mass in a spiral galaxy (such as our own Milky Way) lies in a thin plane or disk passing through the galactic center, and the gravitational pull exerted by that plane on bodies outside the galaxy can be calculated by just the methods we have employed here.

5.17 The gamma function: A commonly occurring function in physics calculations is the gamma function \(\Gamma(a)\), which is defined by the integral $$ \Gamma(a)=\int_{0}^{\infty} x^{n-1} \mathrm{e}^{-x} \mathrm{~d} x . $$ There is no closed-form expression for the gamma function, but one can calculate its value for given \(a\) by performing the integral above numerically. You have to be careful how you do it, however, if you wish to get an accurate answer. a) Write a program to make a graph of the value of the integrand \(x^{n-1} \mathrm{e}^{-x}\) as a function of \(x\) from \(x=0\) to \(x=5\), with three separate curves for \(a=2,3\), and 4 , all on the same axes. You should find that the integrand starts at zero, rises to a maximum, and then decays again for each curve. b) Show analytically that the maximum falls at \(x=a-1\). c) Most of the area under the integrand falls near the maximum, so to get an accurate value of the gamma function we need to do a good job of this part of the integral. We can change the integral from 0 to \(\infty\) to one over a finite range from 0 to 1 using the change of variables in Eq. (5.67), but this tends to squash the peak towards the edge of the \([0,1]\) range and does a poor job of evaluating the integral accurately. We can do a better job by making a different change of variables that puts the peak in the middle of the integration range, around \(\frac{1}{2}\). We will use the change of variables given in Eq. (5.69), which we repeat here for convenience: $$ z=\frac{x}{c+x} . $$ For what value of \(x\) does this change of variables give \(z=\frac{1}{2}\) ? Hence what is the appropriate choice of the parameter \(c\) that puts the peak of the integrand for the gamma function at \(z=\frac{1}{2}\) ? d) Before we can calculate the gamma function, there is another detail we need to attend to. The integrand \(x^{n-1} \mathrm{e}^{-x}\) can be difficult to evaluate because the factor \(x^{2-1}\) can become very large and the factor \(\mathrm{e}^{-x}\) very small, causing numerical overflow or underflow, or both, for some values of \(x\). Write \(x^{n-1}=\mathrm{e}^{(a-1) \ln x}\) to derive an alternative expression for the integrand that does not suffer from these problems (or at least not so much). Explain why your new expression is better than the old one. e) Now, using the change of variables above and the value of \(c\) you have chosen, write a user-defined function gamma (a) to calculate the gamma function for arbitrary argument \(a\). Use whatever integration method you feel is appropriate. Test your function by using it to calculate and print the value of \(\Gamma\left(\frac{3}{2}\right)\), which is known to be equal to \(\frac{1}{2} \sqrt{\pi} \simeq 0.886\). f) For integer values of \(a\) it can be shown that \(\Gamma(a)\) is equal to the factorial of \(a-\) 1. Use your Python function to calculate \(\Gamma(3), \Gamma(6)\), and \(\Gamma(10)\). You should get answers closely equal to \(2 !=2,5 !=120\), and \(9 !=362880\).

Heat capacity of a solid Debye's theory of solids gives the heat capacity of a solid at temperature \(T\) to be $$ C_{V}=9 V \rho k_{B}\left(\frac{T}{\theta_{D}}\right)^{3} \int_{0}^{\otimes_{D} / T} \frac{x^{4} \mathrm{e}^{x}}{\left(e^{x}-1\right)^{2}} \mathrm{~d} x $$ where \(V\) is the volume of the solid, \(\rho\) is the number density of atoms, \(k_{B}\) is Boltzmann's constant, and \(\theta_{D}\) is the so-called Debye temperature, a property of solids that depends on their density and speed of sound. a) Write a Python function \(\mathrm{cv}(\mathrm{T})\) that calculates \(C_{V}\) for a given value of the temperature, for a sample consisting of 1000 cubic centimeters of solid aluminum, which has a number density of \(\rho=6.022 \times 10^{28} \mathrm{~m}^{-3}\) and a Debye temperature of \(\theta_{D}=428 \mathrm{~K}\). Use Gaussian quadrature to evaluate the integral, with \(N=50\) sample points. b) Use your function to make a graph of the heat capacity as a function of temperature from \(T=5 \mathrm{~K}\) to \(T=500 \mathrm{~K}\).

Period of an anharmonic oscillator The simple harmonic oscillator crops up in many places. Its behavior can be studied readily using analytic methods and it has the important property that its period of oscillation is a constant, independent of its amplitude, making it useful, for instance, for keeping time in watches and clocks. Frequently in physics, however, we also come across anharmonic oscillators, whose period varies with amplitude and whose behavior cannot usually be calculated analytically. A general classical oscillator can be thought of as a particle in a concave potential well. When disturbed, the particle will rock back and forth in the well: The harmonic oscillator corresponds to a quadratic potential \(V(x) \propto x^{2}\). Any other form gives an anharmonic oscillator. (Thus there are many different kinds of anharmonic oscillator, depending on the exact form of the potential.) One way to calculate the motion of an oscillator is to write down the equation for the conservation of energy in the system. If the particle has mass \(m\) and position \(x\), then the total energy is equal to the sum of the kinetic and potential energies thus: $$ E=\frac{1}{2} m\left(\frac{\mathrm{d} x}{\mathrm{~d} t}\right)^{2}+V(x) $$ Since the energy must be constant over time, this equation is effectively a (nonlinear) differential equation linking \(x\) and \(t\). Let us assume that the potential \(V(x)\) is symmetric about \(x=0\) and let us set our anharmonic oscillator going with amplitude \(a\). That is, at \(t=0\) we release it from rest at position \(x=a\) and it swings back towards the origin. Then at \(t=0\) we have \(\mathrm{d} x / \mathrm{d} t=0\) and the equation above reads \(E=V(a)\), which gives us the total energy of the particle in terms of the amplitude. a) When the particle reaches the origin for the first time, it has gone through one quarter of a period of the oscillator. By rearranging the equation above for \(\mathrm{d} x / \mathrm{d} t\) and then integrating with respect to \(t\) from 0 to \(\frac{1}{4} T\), show that the period \(T\) is given by $$ T=\sqrt{8 m} \int_{0}^{a} \frac{\mathrm{d} x}{\sqrt{V(a)-V(x)}} $$ b) Suppose the potential is \(V(x)=x^{4}\) and the mass of the particle is \(m=1 .\) Write a Python function that calculates the period of the oscillator for given amplitude a using Gaussian quadrature with \(N=20\) points, then use your function to make a graph of the period for amplitudes ranging from \(a=0\) to \(a=2\). c) You should find that the oscillator gets faster as the amplitude increases, even though the particle has further to travel for larger amplitude. And you should find that the period diverges as the amplitude goes to zero. How do you explain these results?

See all solutions

Recommended explanations on Physics Textbooks

View all explanations

What do you think about this solution?

We value your feedback to improve our textbook solutions.

Study anywhere. Anytime. Across all devices.

Sign-up for free