I need to round some double values to four decimals maximum, and then send them over XML-RPC using this library.
What I've done so far is the following:
First of all I have a round function:
double roundD(double x, unsigned int precision = 4)
{
return round(x * pow(10.0, double(precision))) / pow(10.0, double(precision));
}
and it works fine, according to this.
In my application, I've a set method setXValue that takes a double and a toXmlRpc() method to output an XmlRpcValue object:
class Point{
public:
Point(double x, double y) {m_x = x; m_y=y;}
void Point::setXValue(double x)
{
m_x = roundD(x);
}
XmlRpcValue Point::toXmlRpc() const
{
XmlRpcValue xmlrpcvalue;
xmlrpcvalue["x"] = m_x;
return xmlrpcvalue;
}
private:
double m_x;
double m_y;
What I store in the XML-RPC value is not a rounded double. In fact, when receiving that XML-RPC answer, I see good values like 0.3488, 0.1154 for example, but also values in the form of 9.059900000000001 or 8.990399999999999.
I'm sure my roundD function works fine (I've tested it in the C++ playground) so where the issue is located?
I cannot store the value in the XmlRpcValue object like this:
char str[80];
sprintf(str, "%.4f", m_x);
xmlrpcvalue["x"] = str;
Otherwise I would change the xml-rpc data type, and that is not correct.
Try using this member function of XmlRpcValue:
setDoubleFormat (const char *f)
//Specify the format used to write double values.
Related
I come across this code in my older books. I tried to run it in Visual Studio 2019, but it gave me an error:
volume function does not take zero arguments
Is this because the code is old, or the code is wrong?
#include<iostream>
using namespace std;
class Cylinder
{
private:
const double pi = 3.14;
double r, h;
public:
void ro(double radius) {
r = radius;
}
void ho(double height) {
h = height;
}
double volume(double r, double h)
{
return pi * r * r * h;
}
};
int main()
{
Cylinder s;
s.ro(1);
s.ho(2);
cout << s.volume();
return 0;
}
The code is wrong. The volume function is declared to take two double arguments and the C++ compiler expects it to be called that way.
I'm not aware of any C++ compiler of any age that would accept that code.
It looks like maybe the function is trying to use the member variables r and h, in which case you should probably remove the parameters from the declaration of volume.
The code is wrong.
When calling a function, you must pass in as many values as there are parameters declared. You can't skip parameters, unless they are declared with default values, which is not the case here.
Given the way main() is using Cylinder in this example, the 2 input parameters need to be removed completely, since they are shadowing the r and h class members that are being set by the ro() and ho() methods.
double volume()
{
return pi * r * r * h;
}
Now the call to cout << s.volume(); will work as expected.
I believe the code is wrong.
If you had default argument on the method.
E.g something like this:
double volume(double r = 0, double h = 0)
{
return pi * r * r * h;
}
It would work when you call it without parameters.
I am trying to create Voronoi diagram for some given points. Each points have different attributes and I want to denote it as color. To map my own Point structure with Boost Point concept, I have written some code. I have the following setup:
struct Point {
double a;
double b;
Point(double x, double y) : a(x), b(y) {}
};
// This Point structure is mapped to Boost Point concept. Code emitted
I have another structure as :
struct Point_Collection {
Point xy(double x, double y);
short color;
};
Visual Studio created an automatic definition as :
Point Point_Collection::xy(double x, double y)
{
return Point();
}
Now if I try to instantiate an object of Point_collection as:
std::vector<Point_Collection> *test;
test = new std::vector<Point_Collection>();
Point_Collection xy_color;
for (int i = 0; i < 5000; i++) {
xy_color.xy(rand() % 1000, rand() % 1000);
xy_color.color = rand() % 17;
test->push_back(xy_color);
}
I get an error.
error C2512: 'Point': no appropriate default constructor available
Can someone point me in the right direction why is this happening?
Point xy(double x, double y); declares a member function in Point_Collection that is identified by xy, accepts two doubles and returns a Point object by value.
If you want a simple aggregate that holds a point, the C++11 and onward way would be to define it like this:
struct Point_Collection {
Point xy;
short color;
};
Point_Collection xy_color{ { rand()%100, rand()%100 }, static_cast<short>(rand()%16)};
The above is a simple aggregate initialization using value initialization syntax. You should prefer it for two reasons:
It will not allow narrowing conversions. (Which int to short is, therefore the cast).
It's easy to implement. It requires no typing if your class has all public members.
(Also rand has better alternatives in C++11, check out the header <random>)
If you don't have access to C++11, then you can either write a constructor for Point_Collection.
struct Point_Collection {
Point xy;
short color;
Point_Collection(Point xy, short color)
: xy(xy), color(color) {}
};
Point_Collection xy_color (Point(...,...), ...);
Or use aggregate initialization with more verbose syntax:
struct Point_Collection {
Point xy;
short color;
};
Point_Collection xy_color = { Point(rand()%100, rand()%100), rand()%16 };
(Since the above is C++03, rand()%16 will be silently converted to short, despite it being narrowing).
this is a personal project I've been working on and I can't figure out what's going on here (just learning C++). I found answers to very similar problems, but I can't seem to execute the solution. Here is my code with some of the unimportant bits trimmed out:
#include <iostream>
#include <cmath>
#include <complex>
#include <boost/array.hpp>
#include <boost/numeric/odeint.hpp>
#include <gsl/gsl_roots.h>
class Riemann
{
public:
// constructor
Riemann(double leftP, double rightP, double leftrho, double rightrho, \
double leftvx, double rightvx, double leftvy, double rightvy, double gam);
double PL,PR,rhoL,rhoR,vxL,vxR,vyL,vyR,gamma;
// function prototypes
double shockvelocity(double Pg, int sign);
double rarefactionvelocity(double Pg, int sign);
void RfODE(const boost::array<double,6> &vrhovt, \
boost::array<double,6> &dvrhovtdp, double t);
// ~Riemann();
};
Riemann::Riemann(double leftP, double rightP, double leftrho, double rightrho, \
double leftvx, double rightvx, double leftvy, double rightvy, double gam){
// constructs Riemann public variables
}
double Riemann::shockvelocity(double Pg,int sign){
// calculate a shock velocity, not important here...
}
void Riemann::RfODE(const boost::array<double,6> &vrhovt, \
boost::array<double,6> &dvrhovtdp, double t){
// calculates the ODE I want to solve
}
double Riemann::rarefactionvelocity(double Pg, int sign){
double dpsize=0.00001;
double P,rho,vx,vy,vtest;
//
boost::array<double,6> vrhovt = {vx,rho,vy,double(sign),P,gamma}; // initial conditions
boost::numeric::odeint::integrate(std::bind(&Riemann::RfODE,std::ref(*this),std::placeholders::_1,
std::placeholders::_2, std::placeholders::_3),vrhovt,P,Pg,dpsize);
std::cout<<"vRarefaction="<<vrhovt[0]<<std::endl;
return vrhovt[0];
}
double FRiemann(double Pg, void* Riemannvalues){
Riemann* Rvals = (Riemann*)Riemannvalues;
// calls on Riemann::rarefactionvelocity at some point
}
int main(){
double PL= 1000.0;
double PR= 0.01;
double rhoL= 1.0;
double rhoR= 1.0;
double vxL= 0.0;
double vxR= 0.0;
double vyL= 0.0;
double vyR= 0.0;
double gam = 5.0/3.0;
// calls FRiemann to get a root
}
What's happening is the code is going through, calling Riemann::rarefactionvelocity just fine, but for some reason RfODE is never executed (ex. print statements in this function never execute) and the value for vrhovt[0] returned is of course the value it began with, vx. No compiler errors, either (using gcc 4.8.1 and -std=c++11 and -O2 tags) This is very strange because I've tested the rarefaction-specific functions on their own (outside of the Riemann class) and they work -- the problem seems to be that they're in this class. Given how Riemann solvers work, though, I had my reasons for making a class out of these functions and really would like to find a way to make this work without doing a massive rewrite and changing the class structure.
Any help is much appreciated! Thank you! : )
It might be possible that P is not initialized correctly. At least I don't see it in your code. P needs to be smaller than PG otherwise your are already behind your the end of the integration.
Also, don't use bind, use a lambda instead. I think bind is somehow obsolete in C++11/C++14. It might be possible that bind doesn't get the references correct.
double Riemann::rarefactionvelocity(double Pg, int sign)
{
// ...
// not tested
using namspace boost::numeric::odeint;
integrate( [this](auto const& x, auto &dxdt ,auto t ) {
this->RfODE(x, dt, t); } ,vrhovt,P,Pg,dpsize);
}
Say I have a C++ function that looks like this:
double myfunction(double a, double b) {
// do something
}
Which I then call like this:
double a = 1.0;
double b = 2.0;
double good_r = myfunction(a, b);
double bad_r = myfunction(b, a); // compiles fine
I would like to make sure that a and b are never provided in the wrong order.
What is the best way to ensure this in C++?
Other languages allow named parameters, like this:
double good_r = myfunction(a=a, b=b);
double bad_r = myfunction(a=b, b=a); // mistake immediately obvious
double bad_r = myfunction(b=b, a=a); // compiles fine
Or perhaps the problem can be partly solved using types, i.e.
double my_type_safe_function(a_type a, b_type b) {
// do something
}
a_type a = 1.0;
b_type b = 2.0;
double good_r = myfunction(a, b);
double bad_r = myfunction(b, a); // compilation error
EDIT: A couple of people have asked what I mean by the "wrong order." What I mean is that, in real code a and b have some significance. For example, the arguments might instead be height and width. The difference between them is very important for the function to return the correct result. However, they are both floats and they both have the same dimensions (i.e. a length). Also, there is no "obvious" order for them. The person writing the function declaration may assume (width, height) and the person using the function may assume (height, width). I would like a way to ensure this doesn't happen by mistake. With two parameters it is easy to be careful with the order, but in a large project and with up to 6 arguments mistakes creep in.
Ideally I would like the checks to be done at compile time, and for there to be no performance hit (i.e. at the end of the day they are treated as plain old floats or whatever).
How about this:
struct typeAB {float a; float b; };
double myfunction(typeAB p) {
// do something
return p.a - p.b;
}
int main()
{
typeAB param;
param.a = 1.0;
param.b = 2.0;
float result = myfunction(param);
return 0;
}
Of course, you can still mess up when you assign your parameter(s) but that risk is hard to avoid :)
A variant is to have one struct per "new" type, and then make them go away in optimized builds using macros.
Something along these lines (only slightly tested, so it could be way off):
#define SAFE 0
#if SAFE
#define NEWTYPE(name, type) \
struct name { \
type x; \
explicit name(type x_) : x(x_) {}\
operator type() const { return x; }\
}
#else
#define NEWTYPE(name, type) typedef type name
#endif
NEWTYPE(Width, double);
NEWTYPE(Height, double);
double area(Width w, Height h)
{
return w * h;
}
int main()
{
cout << area(Width(10), Height(20)) << endl;
// This line says 'Could not convert from Height to Width' in g++ if SAFE is on.
cout << area(Height(10), Width(20)) << endl;
}
I think you already provided the easiest solution, using types.
One alternative could be using a builder class and method chaining.
Like:
class MyfunctionBuilder {
MyFunctionBuilder & paramA(double value);
MyFunctionBuilder & paramB(double value);
double execute();
(...)
}
Which you would use like this:
double good_r = MyFunctionBuilder().paramA(a).paramB(b).execute();
But this is a lot of extra code to write!
What is the "wrong order" actually? In this example of yours
double myfunction(double a, double b) {
// do something
}
double a = 1.0;
double b = 2.0;
double good_r = myfunction(a, b);
double bad_r = myfunction(b, a);
how do you actually want to know if this is the right order? What if the variables would be named "quapr" and "moo" instead of "a" and "b"? Then it would be impossible to guess whether the order is right or wrong just by looking at them.
With this in mind, you can do at least two things. First, is to give meaningfull names to the arguments, e.g.
float getTax( float price, float taxPercentage )
instead of
float getTax( float a, float b )
Second, do the necessary checks inside:
float divide( float dividend, float divisor )
{
if( divisor == 0 )
{
throw "omg!";
}
}
It is possible to do more complex checks, such as making a functor, and setting it's parameters explicitly, but in most of the cases that just complicates things without much benefit.
I have a class CS which is to represent the co-ordinate system in 3D i.e.(x, y, z)
class CS
{
private:
double x;
double y;
double z;
}
CS::CS()
{
x = NULL;//this causes x = 0//i want the address of x to be 0x000000 & not x = 0
y = NULL;
z = NULL:
}
I want that the user can create a CS (0, 0, 0).
In the constructor i want to initialise the address of x, y & z to NULL.
this is to differentiate between the user defined (0, 0, 0) & the default value.
I am creating the objects of CS dynamically, so there is no point in using the following code:
class CS
{
private:
double *x;
double *y;
double *z;
}
CS:CS()
{
x = new double;
x = NULL;
//same for y & z
}
Primarily, i want to manually assign 0x000000 address to any variable(int or double or char) without using pointers.
any suggestions?
You can't change the positions of x,y,and z to be NULL, since there positions will always be offsets from the CS object. They will always exist. It's not that CS has an x like you have a car, it's like CS has an x like you have a head. You can't not have a head. If they were integers, you would have to make them pointers (like you said you didn't want to do), because that would be the only way to tell uninitialized from initialized. However, doubles have a magic value that is rarely used:
CS:CS()
: x(std::numeric_limits<double>::quiet_NaN())
: y(std::numeric_limits<double>::quiet_NaN())
: z(std::numeric_limits<double>::quiet_NaN())
{ }
Users probably won't be setting x, y, and z to (NOT A NUMBER) intentially.
Primarily, i want to manually assign 0x000000 address to any variable(int or double or char) without using pointers. any suggestions?
That's not what you want. What you want is the ability to detect whether a variable has been set or not.
Others have suggested things like using a specific floating-point value to detect the uninitialized state, but I suggest employing Boost.Optional. Consider:
class CS
{
private:
boost::optional<double> x;
boost::optional<double> y;
boost::optional<double> z;
}
boost::optional either stores the type you give to the template parameter or it stores nothing. You can test the difference with a simple boolean test:
if(x)
{
//Has data
}
else
{
//Has not been initialized
}
The downside is that accessing the data is a bit more complex:
x = 5.0; //Initialize the value. x now has data.
y = 4.0 * x; //Fails. x is not a double; it is an optional<double>.
y = 4.0 * (*x); //Compiles, but only works at runtime if x has a value.
You have several options:
Use pointers.
Use a boolean flag alongside each variable indicating whether the variable has been set.
If the range of allowable values is limited, you could use a special value to stand for "not set". For double, a not-a-number is often a natural candidate. For int and char it's often more tricky to pick a good value.
None of these options is indisputably better than the other two as they involve different tradeoffs. Take your pick.
Why can't you simply do this:
class CS
{
public:
// Constructs a CS initialized to 0, 0, 0
CS() : x(0), y(0), z(0), is_initialized(false) {}
// User defined values
CS(double newX, double newY, double newZ) : x(newX), y(newY), z(newZ), is_initialized(true) {}
private:
double x;
double y;
double z;
// If you need to know that this was initialized a certain way, you could use this suggestion from the comments:
bool is_initialized;
}
If I understand correctly, you want to be able to tell the difference between an invalid, default constructed CS and a valid one with values (0.0, 0.0, 0.0). This is exactly what boost::optional http://www.boost.org/doc/libs/1_47_0/libs/optional/doc/html/index.html is for.
You can't really represent it in the same number of bits without having a sentinel. If 0 is a valid number, then you can't use it. If you try and foist null handling into a value type you will have fundamentally incorrect and unmaintainable code.
When handling nulls properly you would expect to see an interface like this:
struct foo {
virtual ~foo() {}
virtual bool getX(double &val) = 0;
virtual bool getY(double &val) = 0;
virtual bool getZ(double &val) = 0;
};
The implementation can have a flag that it checks before access.
void some_func(foo *f) {
double x, y, z;
if (f->getX(x) && f->getY(y) && f->getZ(z)) {
cout << x << ", " << y << ", " << z << endl;
} else {
throw std::logic_error("expected some values here");
}
}
You don't want to use an invalid value and not know it. Having to check the return values is tedious obviously, but it gives you the most control. You could also have helpers or overloads that would throw if they weren't valid.
struct bar {
double getX() {
if (!valid)
throw std::logic_error("bar is not valid");
return x;
}
bool valid;
double x, y, z;
}
For me, the difference between foo and bar is that low level code handling the data shouldn't enforce a policy of whether the data is there or not. At higher levels of abstraction you can and should have expectations of whether the data should valid when you go to use it. The both can exist in a system, but foo is necessary.
One way to get the semantics of what you want would be to have the datatype of the coordinates be a type that carries with it a value indicating whether it has been assigned. Something like this.
template<typename T>
class CoordinateValue {
public:
CoordinateValue() : uninitialized(true), val(0) {}
CoordinateValue(T x) : uninitialized(false), val(x) {}
void setVal(T x) {val = x; uninitialized= false}
// Trivial getters
private:
T val;
bool uninitialized;
};
I'd prefer something like this over cuter methods unless memory is really scarce for some reason.
If the coordinates are either all default or all set, then you can have a single flag rather than a coordinate datatype that includes the flag.
I want that the user can create a CS (0, 0, 0). In the constructor i
want to initialise the address of x, y & z to NULL. this is to
differentiate between the user defined (0, 0, 0) & the default value.
I am creating the objects of CS dynamically, so there is no point in
using the following code:
This is the problem. Firstly, default value? What default value? Why should there be a default value? That's wrong. And secondly, it's fundamentally impossible for you to change the address of any variable.
What you want cannot be done and even if it could, it would be a horrendously bad idea.
You can't change the address of a variable. And you can't assign pointer values (like NULL, or nullptr in C++) to a variable of a non-pointer type, such as double.