Newton's Method in C++ - c++

I am trying to translate f(x) = x − e-(x2) in c++ source code but I keep getting errors. I have tried :
double f(double x)
{
exp = pow(-x, 2);
double result = x - exp;
return x;
};
Any insight?
If it helps, I am using Code::Blocks

#include <math.h>
double f(double x)
{
return x - exp(-(x*x));
}

Related

How to use the bisection method in boost C++ for a function with multiple arguments

I have below function in C++
#include <cmath>
#include <utility>
#include <iostream>
#include <boost/math/tools/roots.hpp>
double my_fn(double x, double y)
{
return x*x - y - 1;
};
int main() {
double min_x = 0.0; // min value of domain of x
double max_x = 10.0; // max value of domain of x
double y = 1;
// how to use boost's bisection to find solution of my_fn for y = 1
return (0);
}
As you see my_fn takes 2 arguments x and y. However I want to find solution of this function given y = 1.
Can you please help to find solution using bisection method?
#include <cmath>
#include <utility>
#include <iostream>
#include <boost/math/tools/roots.hpp>
double my_fn(double x, double y)
{
return x*x - y - 1;
};
int main() {
double min_x = 0.0; // min value of domain of x
double max_x = 10.0; // max value of domain of x
double y = 1;
auto x = boost::math::tools::bisect(
[y](double x){ return my_fn(x,y); },
min_x,
max_x,
[](double x,double y){return abs(x-y) < 0.01;}
);
std::cout << "The minimum is between x=" << x.first << " and x=" << x.second;
// how to use boost's bisection to find solution of my_fn for y = 1
return (0);
}
bisect is a template. The first parameter is a callable (the function to minimize), then the initial bracket (min and max) and the last parameter is a callable that evaluates the stop condition.
Alternatively you can write a function:
double my_fn_y1(double x) {
return my_fn(x,1);
}
and minimize that.
PS: The function does not return the solution, but rather the final interval which makes the stop condition true. The real solution is somewhere in that interval.
You can use a lambda (with good chance that the compiler inlines everything), like this:
#include <boost/math/tools/roots.hpp>
#include <iostream>
double my_fn(double x, double y) { return x * x - y - 1; };
int main()
{
double min_x = 0.0; // min value of domain of x
double max_x = 10.0; // max value of domain of x
double y = 1;
std::pair<double, double> result =
boost::math::tools::bisect([y](double x) { return my_fn(x, y); },
min_x,
max_x,
boost::math::tools::eps_tolerance<double>());
std::cout << "Result " << result.first << ", " << result.second;
return 0;
}
which prints:
Result 1.41421, 1.41421
You can read about lambda and lambda capture here: cpp.reference lambda section.

Changing the whole part of a number with the decimal part [duplicate]

I have a program in C++ (compiled using g++). I'm trying to apply two doubles as operands to the modulus function, but I get the following error:
error: invalid operands of types 'double' and 'double' to binary 'operator%'
Here's the code:
int main() {
double x = 6.3;
double y = 2;
double z = x % y;
}
The % operator is for integers. You're looking for the fmod() function.
#include <cmath>
int main()
{
double x = 6.3;
double y = 2.0;
double z = std::fmod(x,y);
}
fmod(x, y) is the function you use.
You can implement your own modulus function to do that for you:
double dmod(double x, double y) {
return x - (int)(x/y) * y;
}
Then you can simply use dmod(6.3, 2) to get the remainder, 0.3.
Use fmod() from <cmath>. If you do not want to include the C header file:
template<typename T, typename U>
constexpr double dmod (T x, U mod)
{
return !mod ? x : x - mod * static_cast<long long>(x / mod);
}
//Usage:
double z = dmod<double, unsigned int>(14.3, 4);
double z = dmod<long, float>(14, 4.6);
//This also works:
double z = dmod(14.7, 0.3);
double z = dmod(14.7, 0);
double z = dmod(0, 0.3f);
double z = dmod(myFirstVariable, someOtherVariable);

About 200 Errors When Using cmath in Visual Studio 2015

Trying to get code that was compilable in g++ to compile in VS2015. I looked around SO & Google with not much luck, yet cmath is documented in MSDN. I'm guessing I'm missing something really obvious or simple.
cmath is throwing a lot of errors most of the errors I'm getting during compilation, and half are in the form:
the global scope has no "<function>"
others are in the form
'<function>': redefinition; different exception specification
'<function>': identifier not found
'<function>': is not a member of "global namespace"
I don't understand why these errors are being thrown, but, if I use math.h, most of my compilation errors go away (including some in other standard libs that are crapping out, too).
Edit: As requested, the code. I'm using the sqrt & pow functions:
#include "vector.h"
#include <cmath>
using namespace vectormath;
vector::vector()
{
this->_x = 0;
this->_y = 0;
this->_z = 0;
this->_length = 0;
}
vector::vector(float x, float y, float z)
{
this->_x = x;
this->_y = y;
this->_z = z;
this->_length = sqrt(pow(_x, 2) + pow(_y, 2) + pow(_z, 2));
}
vector * vectormath::crossproduct(vector * a, vector * b)
{
vector * result = new vector();
result->_x = a->_y * b->_z - a->_z * b->_y;
result->_y = a->_z * b->_x - a->_x * b->_z;
result->_z = a->_x * b->_y - a->_y * b->_x;
return result;
}
point::point()
{
this->_x = 0.0;
this->_y = 0.0;
this->_z = 0.0;
}
point::point(float x, float y, float z)
{
this->_x = x;
this->_y = y;
this->_z = z;
}
float vectormath::dotproduct(vector a, vector b)
{
return a._x * b._x + a._y * b._y + a._z * b._z;
}
vector * vectormath::add(point * a, vector * b)
{
vector * c = new vector();
c->_x = a->_x + b->_x;
c->_y = a->_y + b->_y;
c->_z = a->_z + b->_z;
return c;
}
Edit: and vector.h
namespace vectormath
{
struct vector
{
float _x;
float _y;
float _z;
float _length;
vector();
vector(float x, float y, float z);
};
struct point
{
float _x;
float _y;
float _z;
point();
point(float x, float y, float z);
};
vector * crossproduct(vector*, vector*);
float dotproduct(vector a, vector b);
vector * add(point * a, vector * b);
}
The difference between
#include <math.h>
and
#include <cmath>
is that the former puts things like sqrt and pow into the global namespace (i.e., you refer to them just by saying sqrt or pow) and the latter puts them into namespace std (i.e., you refer to them by saying std::sqrt or std::pow).
If you want not to have to prefix them with std:: all the time, you can put individual ones in the global namespace explicitly:
using std::sqrt;
or (though this is not recommended) you can pull in the whole of std like this:
using namespace std;
The trouble with that is that there are a lot of names in std and you probably don't really want them all.

Infinite loop calculating cubic root

I'm trying to make a function that calculates the cubic root through Newton's method but I seem to have an infinite loop here for some reason?
#include <iostream>
#include <math.h>
using namespace std;
double CubicRoot(double x, double e);
int main()
{
cout << CubicRoot(5,0.00001);
}
double CubicRoot(double x, double e)
{
double y = x;
double Ynew;
do
{
Ynew = y-((y*y)-(x/y))/((2*y)+(x/(y*y)));
cout << Ynew;
} while (abs(Ynew-y)/y>=e);
return Ynew;
}
You have not updated your y variable while iteration.
Also using abs is quite dangerous as it could round to integer on some compilers.
EDIT
To clarify what I've mean: using abs with <math.h> could cause implicit type conversion problems with different compiles (see comment below). And truly c++ style would be using the <cmath> header as suggested in comments (thanks for that response).
The minimum changes to your code will be:
double CubicRoot(double x, double e)
{
double y = x;
double Ynew = x;
do
{
y = Ynew;
Ynew = y-((y*y)-(x/y))/((2*y)+(x/(y*y)));
cout << Ynew;
} while (fabs(Ynew-y)/y>=e);
return Ynew;
}
You can change
Ynew = y-((y*y)-(x/y))/((2*y)+(x/(y*y)));
to the equivalent, but more recognizable expression
Ynew = y*(y*y*y+2*x)/(2*y*y*y+x)
which is the Halley method for f(y)=y^3-x and has third order convergence.

Round a double to the closest and greater float

I want to round big double number (>1e6) to the closest but bigger float using c/c++.
I tried this but I'm not sure it is always correct and there is maybe a fastest way to do that :
int main() {
// x is the double we want to round
double x = 100000000005.0;
double y = log10(x) - 7.0;
float a = pow(10.0, y);
float b = (float)x;
//c the closest round up float
float c = a + b;
printf("%.12f %.12f %.12f\n", c, b, x);
return 0;
}
Thank you.
Simply assigning a double to float and back should tell, if the float is larger. If it's not, one should simply increment the float by one unit. (for positive floats). If this doesn't still produce expected result, then the double is larger than supported by a float, in which case float should be assigned to Inf.
float next(double a) {
float b=a;
if ((double)b > a) return b;
return std::nextafter(b, std::numeric_limits<float>::infinity());
}
[Hack] C-version of next_after (on selected architectures would be)
float next_after(float a) {
*(int*)&a += a < 0 ? -1 : 1;
return a;
}
Better way to do it is:
float next_after(float a) {
union { float a; int b; } c = { .a = a };
c.b += a < 0 ? -1 : 1;
return c.a;
}
Both of these self-made hacks ignore Infs and NaNs (and work on non-negative floats only). The math is based on the fact, that the binary representations of floats are ordered. To get to next representable float, one simply increments the binary representation by one.
If you use c99, you can use the nextafterf function.
#include <stdio.h>
#include <math.h>
#include <float.h>
int main(){
// x is the double we want to round
double x=100000000005.0;
float c = x;
if ((double)c <= x)
c = nextafterf(c, FLT_MAX);
//c the closest round up float
printf("%.12f %.12f\n",c,x);
return 0;
}
C has a nice nextafter function which will help here;
float toBiggerFloat( const double a ) {
const float test = (float) a;
return ((double) test < a) ? nextafterf( test, INFINITY ) : test;
}
Here's a test script which shows it on all classes of number (positive/negative, normal/subnormal, infinite, nan, -0): http://codepad.org/BQ3aqbae (it works fine on anything is the result)