Our assignment asks us to create a python program to plot the Weierstrass function:

Weierstrass function is an example of a pathological real-valued function on the real line. The function has the property of being continuous everywhere but differentiable nowhere.The function was defined as a Fourier series, where $0 < a < 1$, $b$ is a positive odd integer, and $ab > 1 + 3\pi/2$:

$$f(x) = \sum_{n=0}^\infty a^n \cos(b^n \pi x)$$

In practice, the higher of the Fourier series' order, the more accurate result of $f(x)$ we get. And when we consider the accuracy at a specific region of $x$, the definition of the average error as the following:

$$f(x) = \frac{1}{N_{\rm num}} \sum_{i}^{N_{\rm num}} \left( f^{n+1}(x_i) - f^{n}(x_i) \right)^2 $$

where $N_{\rm num}$ is the total number of $x$ we calculate, $f^n(x)$ is the value of $f(x)$ with the order of $n$.

Please write a python program to plot this function with the parameters $a = 0:5$; $b = 13$; $x$ is [0; 3:3]; $N_{\rm num}= 10^3$.

And find the proper order ($n$) where the average error is smaller than $10^{-8}$.

Now, I have already written the function for the Fourier series:

def f(x, n):
y = 0
for i in range(n):
    y = y + (0.5**n)*np.cos(np.pi*x*13**n)
return y

But I have some problem writing the error function. I have written something like this, but I can't figure out how to put the $i$ and $x_i$ inside the summation part(I don't know what is $i$ and where it comes from):

def error(x, N):
N = 10**3
error_sum = 0
for n in range(N):
    error_sum = error_sum + (f(x, n + 1) - f(x, n))**2
return error_sum/N

Can someone help me with the problem and also check whether my first function is correct or not?

  • 1
    $\begingroup$ You're summing over $n$ in your code, but the sum runs over $i$ in the formula. You have $\sum_{n=1}^{N} (f^{n+1}(x_i) - f^n(x_i))^2$ in your code, this defines a function of $x_i$. But in the formula, it's $\sum_{i=1}^{N}(f^{n+1}(x_i) - f^n(x_i))^2$, in which $x_i$'s are given (in the problem description: $x\in[0,3]$, $N=10^3$), and this is a function of $n$. $\endgroup$ – Kirill May 1 at 18:13

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.