File size: 2,501 Bytes
5a600cf | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 | /*--------------------------------*- C++ -*----------------------------------*\
========= |
\\ / F ield | OpenFOAM: The Open Source CFD Toolbox
\\ / O peration | Website: https://openfoam.org
\\ / A nd | Version: dev
\\/ M anipulation |
\*---------------------------------------------------------------------------*/
FoamFile
{
format ascii;
class dictionary;
object testCalcNewton;
}
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
// Find the root of f(x) = x + B*x/sqrt(1 + sqr(x)) - A
// using Newton-Raphson iteration
A 1;
B 1;
x #stream
#{
// Lookup the coefficients
const scalar A = $A;
const scalar B = $B;
// Initial guess for x
scalar x = 0;
scalar x0 = x;
do
{
// Store the previous iteration x for the convergence check
x0 = x;
// Temporary sub-function evaluations
const scalar f1 = 1 + sqr(x);
const scalar f2 = sqrt(f1);
// Evaluate the function
const scalar f = x + B*x/f2 - A;
// Evaluate the derivative
const scalar df = 1 + B/(f1*f2);
// Update x
x = x0 - f/df;
// Test for convergence
} while (mag(x - x0) > 1e-6);
os << x;
#};
// Write a x-y data for plotting with
// gnuplot -e 'plot "fx.xy" us 1:2 title "f(x)" with lines; pause mouse close'
x0 -2; // Start x
xn 2; // End x
n 101; // Number of x increments
y #codeStream
{
code
#{
// Lookup the coefficients
const scalar A = $A;
const scalar B = $B;
const scalar x0 = $x0;
const scalar xn = $xn;
const int n = $n;
const scalar deltax = (xn - x0)/(n - 1);
Field<scalar> x(n);
Field<scalar> fx(n);
forAll(x, i)
{
x[i] = x0 + i*deltax;
fx[i] = x[i] + B*x[i]/sqrt(1 + sqr(x[i])) - A;
}
// Write the x-y data
setWriter::New("raw")->write
(
".",
"fx",
coordSet(true,"x", x),
"f(x)",
fx
);
#};
codeInclude
#{
#include "setWriter.H"
#};
codeOptions
#{
-I$(LIB_SRC)/sampling/lnInclude
#};
codeLibs
#{
-lsampling
#};
};
#remove y
// ************************************************************************* //
|