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);
Related
I have been using the GSL integration package (gsl_integration.h) in attempt to integrate some multivariable function f(x,y,z) with respect to x between some limit [a,b]. In this example I have as a toy model: f(x,y,z) = xyz
I would like to output the result of this integral using a function
double integral(double a, double b, double y, double z){}
where I can keep y and z arbitrary up until this point. My attempts so far have mostly involved setting y, z equal to a constant in some predefined function and then using the
gsl_integration_qags
function to integrate over that function. However, I want to keep the values of y and z arbitrary until I define them in the above function. The closest I have got so far is as follows
#include <iostream>
#include <iomanip>
#include <fstream>
#include <vector>
#include <string>
#include <cmath>
#include <gsl/gsl_integration.h>
#include<stdio.h>
#include<math.h>
#define PI 3.1415926535897
double integrand(double x, void * params){
double y = *(double *) params;
double z = *(double *) params; // PROBLEM: this just sets z = y
double tmp = x*z*y;
return tmp;
}
double integral(double a, double b, double y, double z){
gsl_integration_workspace * w
= gsl_integration_workspace_alloc (1000);
gsl_function F;
F.function = &integrand; // Set integrand
F.params = &y, &z; // Set the parameters you wish to treat as constant in the integration
double result, error;
gsl_integration_qags (&F, a, b, 0, 1e-7, 1000,
w, &result, &error);
gsl_integration_workspace_free (w); // Free the memory
return result;
}
int main(){
std::cout << "Result "<< integral(0.0,1.0,3.0,5.0)<<std::endl;
}
This gives an output of
Result 4.5
The code sets a = 0.0, b = 1.0, y = z = 3.0 -- I want a = 0.0, b = 1.0, y = 3.0, z = 5.0, which would give a result of 7.5.
I would like to stick to GSL integration rather than boost if possible. I have also consulted https://www.gnu.org/software/gsl/doc/html/integration.html but am none-the-wiser. Any advice would be greatly appreciated, thanks.
I'm taking a guess, but it seems to me you want
double params[] = { y, z };
F.params = params;
and
double y = ((double *)params)[0];
double z = ((double *)params)[1];
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));
}
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.
I have this C++ program:
#include <iostream>
#include <vector>
#include <string>
#include <fstream>
#include <cmath>
using namespace std;
double dx2(int t, int x, int dx)
{
return (-9.8*cos(x));
}
int square(int x)
{
return (x*x);
}
double RK4(float t, float x, float dx, float h)
{
double k1, k2, k3, k4, l1, l2, l3, l4, diff1, diff2;
k1 = h*dx2(t,x,dx);
l1 = h*k1;
k2 = h*dx2(t+h/2,x+l1/2,dx+k1/2);
l2 = h*k2;
k3 = h*dx2(t+h/2,x+l2/2,dx+k2/2);
l3 = h*k3;
k4 = h*dx2(t+h,x+l3,dx+k3);
l4 = h*k4;
diff1 = (l1+2*l2+2*l3+l4)/float(6);
diff2 = (k1+2*k2+2*k3+k4)/float(6);
double OUT[] = {diff1, diff2};
return OUT;
}
int main()
{
double diff, t, t0, t1, x, x0, dx, dx0, h, N;
N = 1000;
t0 = 0;
t = t0;
t1 = 10;
x0 = 0;
x = x0;
dx0 = 0;
dx = dx0;
h = (t1 - t0) / float(N);
for(int i = 1; i<=N; i++) {
diff = RK4(t,x,dx,h);
x = x + diff;
t = t + h;
}
cout << diff;
return 0;
}
As you can see in this program I am solving the 2nd-order differential equation (if there is a way to insert LaTeX equations into my question please tell me):
d2x/dt2= -9.8 cos(x)
which is an example of the simple pendulum's equations of motion. The problem lines are 33 and 34. In it I am attempting to define the first element of the OUT array as diff1 and the second element as diff2. Whenever I compile this program (named example.cpp) I get the error:
g++ -Wall -o "example" "example.cpp" (in directory: /home/fusion809/Documents/CodeLite/firstExample)
example.cpp: In function ‘double RK4(float, float, float, float)’:
example.cpp:33:9: error: cannot convert ‘double*’ to ‘double’ in return
return OUT;
^~~
Compilation failed.
Exactly, since you're returning an array of double's, that decays to double*, but the function is defined to return double. An array of type T and the type T are different types in C++, and they can't be converted between, generally speaking.
In this case, you might be better off with a std::pair<T1, T2> (#include <utility>) since you're using C++ and the standard library, or a structure with two fields of type double. Look up std::pair<> and std::tie<>, the former being used to make pairs of elements of different types, and the latter being used to make tuples of different types of arbitrary size.
When you write the std::pair's elements to std::cout, use the first, second members to access the pair's fields. A std::pair can't be directly output using the overloaded stream operator for std::cout.
Edit:
#include <utility>
std::pair<double, double> RK4(float t, float x, float dx, float h)
{
/* snip */
diff1 = (l1+2*l2+2*l3+l4)/float(6);
diff2 = (k1+2*k2+2*k3+k4)/float(6);
return {diff1, diff2};
}
int main()
{
double x, dx;
/* snip */
for(int i = 1; i<=N; i++) {
std::pair<double, double> diff = RK4(t,x,dx,h);
// or use with C++11 and above for brevity
auto diff = RK4(t,x,dx,h);
x = x + diff.first;
dx = dx + diff.second;
t = t + h;
}
cout << x << " " << dx << "\n" ;
return 0;
}
The return type of your RK4 function is double, which is a single value, but you're trying to return an array of two of them. That won't work. You could change the return type to double* and use new double[2] to allocate an array, but it'd be simpler and safer to use std::pair<double, double> as the return type. Then you can just do return { diff1, diff2 };.
To return several values from function you have several choice:
as all you returned type are identical, you may return array:
std::array<double, 2> RK4(float t, float x, float dx, float h)
{
// ...
return {{diff1, diff2}};
}
or std::vector
std::vector<double> RK4(float t, float x, float dx, float h)
{
// ...
return {{diff1, diff2}};
}
You may return std::tuple or std::pair (limited to 2 elements):
std::pair<double, double> RK4(float t, float x, float dx, float h)
{
// ...
return {{diff1, diff2}};
}
or
std::tuple<double, double> RK4(float t, float x, float dx, float h)
{
// ...
return {{diff1, diff2}};
}
You may also create a custom class
struct RK4Result
{
double diff1;
double diff2;
};
RK4Result RK4(float t, float x, float dx, float h)
{
// ...
return {diff1, diff2};
}
And for type expensive to move, you may use any previous method, but by out parameters:
struct RK4Result
{
double diff1;
double diff2;
};
void RK4(float t, float x, float dx, float h, RK4Result& res)
{
// ...
res = {diff1, diff2};
}
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)