I'm trying to find N root using Newton Raphson method. Here is my implementation for the same...
double derive(int guess, int m, int n) {
return guess - (pow(guess, n)-m)/(n*pow(guess, n-1));
}
double getNRoot(int m, int n) {
double guess = 1;
double nextGuess = derive(guess, m, n);
while (fabs(guess-nextGuess) >= 0.0001) {
guess = nextGuess;
nextGuess = derive(guess, m, n);
printf ("%f %f\n", guess, nextGuess);
}
return nextGuess;
}
It works for many values, but for m=8 and n=4. The guess and nextGuess fluctuates between two values when m=8 and n=4.
2.750000 1.750000
1.750000 2.750000
2.750000 1.750000
...
So what is wrong here?
The derive function returns a double but manipulate int variables. Even if on function call you supply int, you can put doubles in the function prototype to have the proper precision:
double derive(double guess, double m, double n) {
return guess - (pow(guess, n)-m)/(n*pow(guess, n-1));
}
Or at least declare local double variables for the non-pow uses:
double derive(int guess, int m, int n) {
double d_guess = guess;
double d_n = n;
double d_m = m
return d_guess - (pow(d_guess, n)-d_m)/(d_n*pow(d_guess, n-1));
}
You should probably review you whole implementation considering that. That is, use doubles when "real" numbers are needed and "int" where "integer" numbers are used.
Related
#include<iostream>
#include<cmath>
using namespace std;
float san= 0.25 ; float var= 0.75;
int findFact(int n)//factorial
{
return n == 1 ? 1 : n * findFact(n - 1);
}
int findNcR(int n, int r)//combination nCr
{
return findFact(n) / (findFact(n - r) * findFact(r));
}
double prob(int s, int v){ //recursive function for probability
if(s>=5) return 1; if(v>=5) return 0;
double sum = 0;
int m = 5-s;
for( int i=0; i<=m; i++){
sum += prob(s+i,v+m-i)*findNcR(m,i)*pow(san,i)*pow(var,m-i);
}
return sum;
}
int main(){
cout<< prob(2,1);
}
In DEV C++, there is no output printed when I compile and run the above code. I think its because of large fractional values involved. Any idea how I can get the output?
Please check the logic you use in your double prob(int s, int v) method.
You are going to infinity recursive like
S=2 V=1
S=2 V=4
S=2 V=7
The base case for your recursion, s==5 or v==5 is never getting hit. As you call your function with s=2, every time the prob function is called it is setting m to 3, and so on the first iteration of the loop (when i==0) it calls prob with s=2 and v=v+3. As you start with v==1, it successively calls prob(2,1), prob(2,4), prob(2,7), etc... and never gets any further.
I don't know what probability distribution you are trying to code so I can't offer any specific advice on how to fix this.
I want to numerically integrate with boost::math::quadrature::trapezoidal(g, a, b, 1e-6); Here I'm integrating the function g(x). The problem is that I have to perform a double integral. Furthermore, I have 4 variables in the function I want to integrate. 2 of them I pass while integrating (m,n) and the other 2 are the integration variables (r,z). This is the integral I want to compute:
$$
\int_0^b\int_0^af(r,z)\sin{(\frac{n\pi}{a}z)}J_0(\frac{\alpha_{0,m}}{b}r)dzdr
$$
I saw this example Performing 2d numerical integration with Boost Cpp and notices that he uses lambda functions to split the main integrand in 2. so far I have managed this
double integrate(int m, int n)
{
auto f1 = [](double r, double z, int m, int n) { return integrand(r,z,m,n); };
auto f = [&](double r, m) {
auto g = [&](double z, n) {
return f1(r, z);
};
//return gauss_kronrod<double, 61>::integrate(g, 0, a, 5);
return boost::math::quadrature::trapezoidal(g, 0, a, 1e-6);
};
double error;
//double Q = gauss_kronrod<double, 15>::integrate(f, 0, b, 5, 1e-9, &error);
double Q = boost::math::quadrature::trapezoidal(f, 0, b, 1e-6);
//std::cout << Q << ", error estimated at " << error <<std::endl;
return Q;
}
The implementation of the function $f(r,z)$ and the rest of the integral is the following
double initial(double r, double z, int m, int n)
{
return std::sin(M_PI*n*z/a)*std::cyl_bessel_j(0, boost::math::cyl_bessel_j_zero(0,m)*r/b);
}
double integrand(double r,double z,int n,int m)
{
return initial(r,z,m,n)*std::sin(M_PI*n*z/a)*std::cyl_bessel_j(0, boost::math::cyl_bessel_j_zero(0,m)*r/b);
}
Normally the Initial won't need them and n variables but in this case, I need to make some tests.
The problem is that I really don't understand how to split my function like in the example for my problem and perform the integration because boost only accepts 1 variable functions.
Please help
The basic idea is, as usual, to integrate in two steps. For this you first solve the inner integral and make another one-dimensional function out of it, which you then pass again to the integrator.
The lambda is used whenever you want to cut down a multi-parameter function to a single-parameter function. In this case, you put all that is not the integrated variable in the lambda capture.
Here is the pseudo-code:
double integrand(double r,double z, int m,int n, double a, double b)
{
//this is the function you want to integrate
}
double integrate(int m, int n)
{
double a=1.0;
double b=1.0;
auto inner_integral = [m,n,a,b](double z)
{
auto f = [z,m,n,a,b](double r) { return integrand(r,z,m,n,a,b);}
return trapezoidal(f,0,a);
}
return trapezoidal(inner_integral,0,b);
};
You probably don't need to write out the lambda capture, i.e. a reference capture with & will likely work as well (auto inner_integral = [&](double z){...}).
I spent quiet some time looking on the internet to find a solution to this, maybe it's out there but nothing of what I saw helped me.
I have a function !
double integrand(double r, double phi, double theta)
That I want to integrate with some given definite bounds over the three dimensions. I found multiple lines of code on the internet that implement single variable definite integrals numerical schemes. I was thinking to myself "well, I'll just integrate along one dimension after the other".
Algorithmically speaking what I wanted to do was :
double firstIntegral(double r, double phi) {
double result = integrationFunction(integrand,lower_bound,upper_bound);
return result;
}
And simply do it again two more times. This works easily in languages like Matlab where I can create functions handler anywhere but I don't know how to do it in C++. I would have to first define a function that some r and phi will calculate integrand(r, phi, theta) for any theta and make it in C++ a function of one variable only but I don't know how to do that.
How can I compute the triple integral of my three-variables function in C++ using a one -dimensional integration routine (or anything else really...) ?
This is a very slow and inexact version for integrals over cartesian coordinates, which should work with C++11.
It is using std::function and lambdas to implement the numerical integration. No steps have been taken to optimize this.
A template based solution could be much faster (by several orders of magnitude) than this, because it may allow the compiler to inline and simplify some of the code.
#include<functional>
#include<iostream>
static double integrand(double /*x*/, double y, double /*z*/)
{
return y;
}
double integrate_1d(std::function<double(double)> const &func, double lower, double upper)
{
static const double increment = 0.001;
double integral = 0.0;
for(double x = lower; x < upper; x+=increment) {
integral += func(x) * increment;
}
return integral;
}
double integrate_2d(std::function<double(double, double)> const &func, double lower1, double upper1, double lower2, double upper2)
{
static const double increment = 0.001;
double integral = 0.0;
for(double x = lower2; x < upper2; x+=increment) {
auto func_x = [=](double y){ return func(x, y);};
integral += integrate_1d(func_x, lower1, upper1) * increment;
}
return integral;
}
double integrate_3d(std::function<double(double, double, double)> const &func,
double lower1, double upper1,
double lower2, double upper2,
double lower3, double upper3)
{
static const double increment = 0.001;
double integral = 0.0;
for(double x = lower3; x < upper3; x+=increment) {
auto func_x = [=](double y, double z){ return func(x, y, z);};
integral += integrate_2d(func_x, lower1, upper1, lower2, upper2) * increment;
}
return integral;
}
int main()
{
double integral = integrate_3d(integrand, 0.0, 1.0, 0.0, 1.0, 0.0, 1.0);
std::cout << "Triple integral: " << integral << std::endl;
return 0;
}
You can use functors
#include <iostream>
struct MyFunctorMultiply
{
double m_coeff;
MyFunctorMultiply(double coeff)
{
m_coeff = coeff;
}
double operator()(double value)
{
return m_coeff * value;
}
};
struct MyFunctorAdd
{
double m_a;
MyFunctorAdd(double a)
{
m_a = a;
}
double operator()(double value)
{
return m_a + value;
}
};
template<class t_functor>
double calculate(t_functor functor, double value, double other_param)
{
return functor(value) - other_param;
}
int main()
{
MyFunctorMultiply multiply2(2.);
MyFunctorAdd add3(3.);
double result_a = calculate(multiply2, 4, 1); // should obtain 4 * 2 - 1 = 7
double result_b = calculate(add3, 5, 6); // should obtain 5 + 3 - 6 = 2
std::cout << result_a << std::endl;
std::cout << result_b << std::endl;
}
If your concern is just about getting the right prototype to pass to the integration function, you can very well use alternative data passing mechanisms, the simpler of which is using global variables.
Assuming that the order of integration is on theta, then phi, then r, write three functions of a single argument:
It(theta) computes the integrand from the argument theta passed explicitly and the global phi and r.
Ip(phi) computes the bounds on theta from the argument phi passed explicitly and the global r; it also copies the phi argument to the global variable and invokes integrationFunction(It, lower_t, upper_t).
Ir(r) computes the bounds on phi from the argument r passed explicitly; it also copies the r argument to the global variable and invokes integrationFunction(Ip, lower_p, upper_p).
Now you are ready to call integrationFunction(Ir, lower_r, upper_r).
It may also be that integrationFunction supports a "context" argument where you can store what you want.
SHORT How should I reduce (optimize) the number of needed operations in my code?
LONGER For research, I programmed a set of a equations in C++ to output a sequence if it fits the model. On the very inside of the code is this function, called MANY times during run-time:
int Weight(int i, int q, int d){
int j, sum = 0;
if (i <= 0)
return 0;
else if (i == 1)
return 1;
for (j = 1; j <= d; j++){
sum += Weight((i - j), q, d);
}
sum = 1 + ((q - 1) * sum);
return sum;
}
So based on the size of variable d, the size of the index i, and how many times this function is called in the rest of the code, many redundant calculations are done. How should I go about reducing the number of calculations?
Ideally, for example, after Weight(5, 3, 1) is calculated, how would I tell the computer to substitute in its value rather than recalculate its value when I call for Weight(6, 3, 1), given that the function is defined recursively?
Would multidimensional vectors work in this case to store the values? Should I just print the values to a file to be read off? I have yet to encounter an overflow with the input sizes I'm giving it, but would a tail-recursion help optimize it?
Note: I am still learning how to program, and I'm amazed I was even able to get the model right in the first place.
You may use memoization
int WeightImpl(int i, int q, int d); // forward declaration
// Use memoization and use `WeightImpl` for the real computation
int Weight(int i, int q, int d){
static std::map<std::tuple<int, int, int>, int> memo;
auto it = memo.find(std::make_tuple(i, q, d));
if (it != memo.end()) {
return it->second;
}
const int res = WeightImpl(i, q, d);
memo[std::make_tuple(i, q, d)] = res;
return res;
}
// Do the real computation
int WeightImpl(int i, int q, int d){
int j, sum = 0;
if (i <= 0)
return 0;
else if (i == 1)
return 1;
for (j = 1; j <= d; j++){
sum += Weight((i - j), q, d); // Call the memoize version to save intermediate result
}
sum = 1 + ((q - 1) * sum);
return sum;
}
Live Demo
Note: As you use recursive call, you have to be cautious with which version to call to really memoize each intermediate computation. I mean that the recursive function should be modified to not call itself but the memoize version of the function. For non-recursive function, memoization can be done without modification of the real function.
You could use an array to store the intermediate values. For example, for certain d and q have an array that contains the value of Weight(i, q, d) at index i.
If you initialize the array items at -1 you can then do in your function for example
if(sum_array[i] != -1){ // if the value is pre-calculated
sum += sum_array[i];
}
else{
sum += Weight((i - j), q, d);
}
I have created a function that runs Newton's Method for approximating the solution to a function (defined as f). My function returns the better approximation for the root just fine, however it will not display the number of iterates performed in the function properly.
Here is my code:
#include <stdio.h>
#include <math.h>
#include <cstdlib>
#include <iostream>
double newton(double x_0, double newtonaccuracy);
double f(double x);
double f_prime(double x);
int main()
{
double x_0;
double newtonaccuracy;
int converged;
int iter;
printf("Enter the initial estimate for x : ");
scanf("%lf", &x_0);
_flushall();
printf("\n\nEnter the accuracy required : ");
scanf("%lf", &newtonaccuracy);
_flushall();
if (converged == 1)
{
printf("\n\nNewton's Method required %d iterations for accuracy to %lf.\n", iter, newtonaccuracy);
printf("\n\nThe root using Newton's Method is x = %.16lf\n", newton(x_0, newtonaccuracy));
}
else
{
printf("Newton algorithm didn't converge after %d steps.\n", iter);
}
system("PAUSE");
}
double newton(double x_0, double newtonaccuracy)
{
double x = x_0;
double x_prev;
int iter = 0;
do
{
iter++;
x_prev = x;
x = x_prev - f(x_prev)/f_prime(x_prev);
}
while (fabs(x - x_prev) > newtonaccuracy && iter < 100);
if (fabs(x - x_prev) <= newtonaccuracy)
{
int converged = 1;
}
else
{
int converged = 0;
}
return x;
}
double f(double x) {
return ( cos(2*x) - x );
}
double f_prime(double x)
{
return ( -2*sin(2*x)-1 );
}
To be as specific as possible, it is the line:
printf("\n\nNewton's Method required %d iterations for accuracy to %lf.\n", iter, newtonaccuracy);
that is giving me trouble. Every time I run this program it says "Newton's Method required 2686764 iterations..." however this can't be true, provided I have coded correctly (the max number of iterations my code allows is 100).
The variable iter used in main is not initialized or used in the newton function, where you use a local variable iter. You need to either pass iter to newton by reference or find a way to return it from the function.
Here is an example of a function taking some parameters by reference and modifying them:
double foo(double& initial_value, int& iterations)
{
initial_value *= 3.14159;
iterations = 42;
return initial_value/2.;
}
From the caller side:
double x + 12345.;
int iter = 0;
double y = foo(initial_value, iter);