| [15d19f3] | 1 | /* A discrete approximation to the second derivative of a function from R to R.
|
|---|
| 2 | * It is second-order accurate, except at the two endpoints.
|
|---|
| 3 | * To verify with CIVL, type:
|
|---|
| 4 | * civl verify secondDerivative.cvl
|
|---|
| [965b371] | 5 | *
|
|---|
| 6 | * Note: based on Quarteroni, Sacco, Saleri. "Numerical Mathematics" 2nd ed. sec 10.10.1
|
|---|
| [15d19f3] | 7 | */
|
|---|
| [965b371] | 8 |
|
|---|
| [15d19f3] | 9 | $input double dx;
|
|---|
| 10 | $assume(0<dx && dx<1);
|
|---|
| 11 | $input int num_elements;
|
|---|
| 12 | $assume (num_elements > 0);
|
|---|
| 13 | $input double in[num_elements];
|
|---|
| 14 | double out[num_elements];
|
|---|
| 15 | // assume rho:R->R has 4 continuous derivatives on [-1,1]:
|
|---|
| 16 | $abstract $differentiable(4, [-1,1]) $real rho($real x);
|
|---|
| [965b371] | 17 |
|
|---|
| [15d19f3] | 18 | void secondDerivative(int n, double y[], double h, double result[]) {
|
|---|
| 19 | $assume($forall (int i:0..n-1) y[i] == rho(i*h));
|
|---|
| 20 | /*@ loop invariant 1<=i && i<=n-1;
|
|---|
| 21 | @ loop invariant $forall (int j:1..i-1)
|
|---|
| 22 | @ result[j] == (y[j+1] - 2*y[j] + y[j-1])/(h*h);
|
|---|
| 23 | @ loop assigns i, result[1..n-2];
|
|---|
| 24 | @*/
|
|---|
| 25 | for (int i = 1; i < n-1; i++) {
|
|---|
| 26 | result[i] = (y[i+1] - 2*y[i] + y[i-1])/(h*h);
|
|---|
| 27 | }
|
|---|
| 28 | result[0] = (y[2] - 2*y[1] + y[0])/h;
|
|---|
| 29 | result[n-1] = (y[n-3] - 2*y[n-2] - y[n-1])/h;
|
|---|
| 30 | $assert($uniform (int i:1..n-2) result[i] - $D[rho,{x,2}](i*h) == $O(h*h));
|
|---|
| [965b371] | 31 | }
|
|---|
| 32 |
|
|---|
| 33 | void main() {
|
|---|
| [15d19f3] | 34 | secondDerivative(num_elements, in, dx, out);
|
|---|
| [965b371] | 35 | }
|
|---|