Find a continuous function $f:[1,\infty)\to\Bbb R $ such that $f(x) >0 $, $\int_1^\infty f(x)\,dx $ converges and $\int_1^\infty f(x)^2\,dx$ diverges

I'm trying to find an example of a continuous function $f:[1,\infty) \to \Bbb R $ such that $$f(x) >0 $$

$$\int_{1}^{\infty} f(x) \ dx \ \text{converges and } \int_{1} ^{\infty} f(x)^2 dx \ \text{diverges}.$$


Consider at $x=k\in{\mathbb N}_{\geq2}$ a trapezoidal spike of height $k$ with base $\left[k-{2\over k^3},\ k+{2\over k^3}\right]$ and top $\left[k-{1\over k^3},\ k+{1\over k^3}\right]$. Let $f: \>[1,\infty)\to{\mathbb R}$ be the function obtained by "concatenation" of these spikes. The area of the spike at $k$ is ${3\over k^2}$, so that $$\int_1^\infty f(x)\>dx=3 \sum_{k=2}^\infty {1\over k^2}={\pi^2\over2}-3<\infty\ .$$ On the other hand each spike of $f^2$ contains a rectangle of width ${2\over k^3}$ and height $k^2$. It follows that $$\int_1^\infty f^2(x)\>dx\geq\sum_{k=2}^\infty{2\over k}=\infty\ .$$ Add $e^{-x}$ to $f(x)$, as in Sangchul Lee's answer, to make $f$ positive everywhere.


Define $f$ by

$$ f(x) = \mathrm{e}^{-x} + \sum_{n=2}^{\infty} \max\{0, n - n^4|x - n|\}. $$

It is easy to check that

$$ \int_{1}^{\infty} f(x) \, \mathrm{d}x = \int_{1}^{\infty} \mathrm{e}^{-x} \, \mathrm{d}x + \sum_{n=2}^{\infty} \frac{1}{n^2} < \infty. $$

On the other hand,

$$ \int_{1}^{\infty} f(x) \, \mathrm{d}x \geq \sum_{n=2}^{\infty} \int \max\{0, (n - n^4|x - n|)^2 \} \, \mathrm{d}x = \sum_{n=2}^{\infty} \frac{2}{3n} = \infty. $$

The trick is to generate a train of picks. The following graph shows the summation part of $f$:

enter image description here

Picks are constructed to satisfy the following heuristics: Each pick at $x = n$ is of height $\sim n$ and width $\sim n^{-3}$, thus the area is of order $\sim n^{-2}$, when squared, however, its height gets squared and the area becomes of order $\sim n^{-1}$.