I have the following code which is supposed to compute the Euclidean distance between two rectangles. I compiled using GCC 4.7.3 and Boost v1.58.0
#include <iostream>
#include <cmath>
#include <boost/polygon/polygon.hpp>
#include <boost/geometry.hpp>
namespace gtl = boost::polygon;
using namespace boost::polygon::operators;
typedef gtl::rectangle_data<int> LayoutRectangle;
int main(int argc, char** argv)
{
LayoutRectangle t(16740130,29759232,16740350,29760652);
LayoutRectangle n(16808130,29980632,16808350,29982052);
std::cout << gtl::euclidean_distance(t, n) << std::endl;
std::cout << gtl::euclidean_distance(t, n, gtl::HORIZONTAL) << " "
<< gtl::euclidean_distance(t, n, gtl::VERTICAL) << std::endl;
std::cout << gtl::square_euclidean_distance(t, n) << std::endl;
std::cout << std::sqrt(gtl::square_euclidean_distance(t, n)) << std::endl;
std::cout << (int) std::sqrt(gtl::square_euclidean_distance(t, n)) << std::endl;
return 0;
}
The code above produced the following output:
38022.6
67780 219980
52985328800
230185
230185
The correct answer is 230185. Now if I go look at the implementation of euclidean_distance() in the boost polygon library, I see this:
template <typename rectangle_type, typename rectangle_type_2>
typename enable_if< typename gtl_and_3<y_r_edist2, typename is_rectangle_concept<typename geometry_concept<rectangle_type>::type>::type,
typename is_rectangle_concept<typename geometry_concept<rectangle_type_2>::type>::type>::type,
typename rectangle_distance_type<rectangle_type>::type>::type
euclidean_distance(const rectangle_type& lvalue, const rectangle_type_2& rvalue) {
double val = (int)square_euclidean_distance(lvalue, rvalue);
return std::sqrt(val);
}
This looks identical to the std::sqrt(gtl::square_eclidean_distance(t,n)) line in my code which gives the correct answer (230185). So why am I getting 38022.6 with gtl::euclidean_distance()? What am I not seeing here?
Looks like the internal computation is overflowing.
I don't think this is a library bug, the library is used incorrectly with the underlying (unchecked) int type.
(However, there is a different bug in the library that I mention at the end.)
Try using a smaller "integer representation" of the problem:
For example:
LayoutRectangle t(167402,297592,167404,297607);
LayoutRectangle n(168082,299806,168084,299821);
Unfortunately there is no general solution of the problem in integer arithmetic, except 0) using higher precision can buy you something, 1) scaling the problem 2) using multiprecision, 3) using rational arithmetic and integer part
(For floating point the solution is simply normalizing the components, this is how std::abs for std::complex<double> works to avoid floating point overflow)
It is good to use large integers to represent a geometric problem BUT
for this reason, as a workaround, use coordinates that span distance of at most (int)std::sqrt((double)std::numeric_limits<int>::max()/2) = 2^15 = 32768.
Which is a surprisingly small number.
Complete code:
#include <iostream>
#include <cmath>
#include <boost/polygon/polygon.hpp>
#include <boost/geometry.hpp>
int main(){
namespace gtl = boost::polygon;
using namespace boost::polygon::operators;
typedef gtl::rectangle_data<int> LayoutRectangle;
LayoutRectangle t(167401,297592,167403,297606);
LayoutRectangle n(168081,299806,168083,299820);
std::cout << gtl::euclidean_distance(t, n) << std::endl;
std::cout << gtl::euclidean_distance(t, n, gtl::HORIZONTAL) << " "
<< gtl::euclidean_distance(t, n, gtl::VERTICAL) << std::endl;
std::cout << gtl::square_euclidean_distance(t, n) << std::endl;
std::cout << std::sqrt(gtl::square_euclidean_distance(t, n)) << std::endl;
std::cout << (int) std::sqrt(gtl::square_euclidean_distance(t, n)) << std::endl;
}
Output:
2302.1
678 2200
5299684
2302.1
2302
Which is the expected result.
Looking at the code, it seems that there is a bug in the library, not because it gives overflow but because an internal computation is casted to int and not the the underlying generic integer data type. This means that probably even if you use multiprecision integers the results will overflow.
Related
I'm self learning C++ and for some reason "double" doesn't print more than 6 significant digits even after std::setprecision. Do I need to do something else? Most recent version of codeblocks if that helps. This is all the code:
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
std::setprecision(9);
double A = 654321.987;
cout << A << endl;
return 0;
}
You need to feed the result of std::setprecision(9) to std::cout. Otherwise it has no way of knowing what output stream it applies to (and so it won't apply to anything).
std::cout << std::setprecision(9) << A << std::endl;
Or if you prefer you can do it separately:
std::cout << std::setprecision(9);
std::cout << A << std::endl;
What is the correct way to determine if a number (in my case it is a value of power of two calculated by pow(2,n)) is within the limits of values that one variable type can take? I'm doing it like this: if(pow (2,128)>std::numeric_limits<float>::max()), but this is evaluated as true although it is expected that float's maximum value is 2^128 or something more. Is there any better way to do this comparison?
For these kinds of limit checking, you can move the terms around to stay within the limits of the type.
In this case, pow(2,n) == exp(ln(2)*n) mathematically, so, rearranging terms, you can use n > ln(maxval)/ln(2)
You can take the base 2 logarithm of the maximum limit for the type of variable and compare it to n. For example: if(n > std::log2(std::numeric_limits<float>::max()). You probably don't want n to be exactly on the limit though, since I think stuff like floating point error might cause some problems.
First of all can you answer what is the result of pow(2, 128)?
The real question is what is the type for this expression?
The second question is do you know how floating point numbers work?
Take a look on this code to give you a hints:
#include <cmath>
#include <iostream>
#include <limits>
template<class T>
void printInfo(const std::string& desc, T x)
{
std::cout << desc << ' ' << typeid(x).name() << ' ' << x << std::endl;
}
int main()
{
printInfo("A", std::pow(2, 128));
printInfo("B", std::pow(2.0f, 128));
printInfo("A", std::pow(2, 128.0f));
auto c = std::pow(2.0f, 128.0f);
printInfo("C", c);
std::cout << (c > std::numeric_limits<float>::max()) << std::endl;
std::cout << (c == std::numeric_limits<float>::infinity()) << std::endl;
return 0;
}
https://wandbox.org/permlink/bHdKqToDKdC0hSvW
I recommend review documentation of numeric_limits.
And analyze this code:
#include <cmath>
#include <iostream>
#include <limits>
template<class T>
void print2exp()
{
std::cout << typeid(T).name() << '\n';
std::cout << "Radix = " << std::numeric_limits<T>::radix << '\n';
auto maxExp = std::numeric_limits<T>::max_exponent;
std::cout << "Max exp = " << maxExp << '\n';
std::cout << "2^maxExp = " << std::pow(static_cast<T>(2), static_cast<T>(maxExp)) << '\n';
std::cout << "2^(maxExp - 1) = " << std::pow(static_cast<T>(2), static_cast<T>(maxExp - 1)) << '\n';
}
int main()
{
print2exp<float>();
print2exp<double>();
print2exp<long double>();
return 0;
}
https://wandbox.org/permlink/J0hACKUKvKlV8lYK
So proper approach to this is (assuming that radix is 2):
if (x < std::numeric_limits<T>::max_exponent) {
return std::pow(static_cast<T>(2), static_cast<T>(x));
} else {
throw invalid_argument("x is to big to be use as 2^x");
}
I'm trying to use cxx-11's std::unique() to find
the unique elements in an array:
#include <iostream>
#include <algorithm>
#include <vector>
#include <typeinfo>
int main(){
const int n=11;
double x[n],a3[n],a1[n];
x[0]=-0.717778;
x[1]=-0.496843;
x[2]=-0.429063;
x[3]=-0.3596;
x[4]=-0.205607;
x[5]=0.0730536;
x[6]=0.138018;
x[7]=0.585526;
x[8]=2.40104;
x[9]=3.75268;
x[10]=4.55704;
a3[0]=0.790832;
a3[1]=0.569896;
a3[2]=0.502116;
a3[3]=0.432653;
a3[4]=0.343625;
a3[5]=0.512472;
a3[6]=0.56708;
a3[7]=1.01459;
a3[8]=2.32799;
a3[9]=3.67962;
a3[10]=4.48398;
std::cout.precision(10);
std::copy(a3,a3+n,a1);
for(int i=0;i<n;i++) a1[i]+=x[i];
std::sort(a1,a1+n);
for(int i=0;i<n;i++) std::cout << a1[i] << std::endl;
std::cout << "---" << std::endl;
int n_1=std::unique(a1,a1+n)-a1;
std::cout << "length of unique subvector " << n_1 << std::endl;
std::cout << "---" << std::endl;
for(int i=0;i<n_1;i++) std::cout << a1[i] << std::endl;
std::cout << "---" << std::endl;
}
but when I'm running this code (link to coliru)
it returns:
original array
0.073053
0.073053
0.073053
0.073054
0.138018
0.5855256
0.705098
1.600116
4.72903
7.4323
9.04102
---
length of unique subarray 10
---
unique array
0.073053
0.073053
0.073054
0.138018
0.5855256
0.705098
1.600116
4.72903
7.4323
9.04102
---
the unique array still contains a duplicate (and so is wrong)!
what am I doing wrong?
Let's try with a bit more precision, std::cout.precision(20):
0.073052999999999979064
0.073053000000000034575
0.073053999999999952308
0.13801800000000000179
0.58552559999999997942
0.70509800000000000253
1.6001160000000000938
4.7290299999999998448
7.4322999999999996845
9.0410199999999996123
Since most decimal fractions can't be represented exactly by a binary floating point format, slightly different rounding errors cause slightly different results.
In general, you can't expect the results of different floating point calculations to be exactly equal, even if the corresponding calculations applied to mathematical real numbers would be.
You could instead test for "almost equality", carefully choosing a tolerance that's appropriate for your numerical domain. unique allows you to specify your own predicate, instead of a simple equality test:
std::unique(a1,a1+n,[](double x, double y){return std::abs(x-y) < tolerance;});
How about:
int n_1 = std::unique(a1,a1+n,
[](float a, float b)
{
return std::fabs(a-b) < 10e-9;
}
) - a1;
?
Live demo link
I know that you can use:
#define _USE_MATH_DEFINES
and then:
M_PI
to get the constant pi. However, if I remember correctly (comments welcome) this is compiler/platform dependent. So, what would be the most reliable way to use a pi constant that won't cause any problems when I port it from Linux to other systems?
I know that I could just define a float/double and then set it to a rounded pi value myself, but I'd really like to know if there is a designated mechanism.
Meeting C++ has an article on the different options for generating pi: C++ & π they discuss some of the options, from cmath, which is not platform independent:
double pi = M_PI;
std::cout << pi << std::endl;
and from boost:
std::cout << boost::math::constants::pi<double>() << std::endl
and using atan, with constexpr removed since as SchighSchagh points out that is not platform independent:
double const_pi() { return std::atan(1)*4; }
I gathered all the methods into a live example:
#include <iostream>
#include <cmath>
#include <boost/math/constants/constants.hpp>
double piFunc() { return std::atan(1)*4; }
int main()
{
double pi = M_PI;
std::cout << pi << std::endl;
std::cout << boost::math::constants::pi<double>() << std::endl ;
std::cout << piFunc() << std::endl;
}
C++2a pi_v
In C++2a we should get pi_v:
#include <numbers>
#include <iostream>
int main() {
std::cout<< std::numbers::pi_v<double> <<"\n";
}
The function below calculates pi without relying on any libraries at all.
Also, the type of its result is a template parameter.
Platform ueber-independence is stifled a bit because it only works with fixed-precision fractional types -- the calculated value needs to converge and remain constant over 2 iterations.
So if you specify some kind of arbitrary-precision rational or floating-point class which will automatically increase its precision as needed, a call to this function will not end well.
#include <iostream>
#include <iomanip>
namespace golf {
template <typename T> inline T calc_pi() {
T sum=T(0), k8=T(0), fac=T(1);
for(;;) {
const T next =
sum + fac*(T(4)/(k8+T(1))-T(2)/(k8+T(4))-T(1)/(k8+T(5))-T(1)/(k8+T(6)));
if(sum == next) return sum;
sum=next;
fac /= T(16);
k8 += T(8);
} }
static const auto PI = calc_pi<double>();
}
int main() {
std::cout << std::setprecision(16) << golf::PI << std::endl;
return 0;
}
I am using boost spirit to parse some text files into a data structure and now I am beginning to generate text from this data structure (using spirit karma).
One attempt at a data structure is a boost::fusion::map (as suggested in an answer to
this question). But although I can use boost::spirit::qi::parse() and get data in it easily, when I tried to generate text from it using karma, I failed.
Below is my attempt (look especially at the "map_data" type). After some reading and playing around with other fusion types, I found boost::fusion::vector and BOOST_FUSION_DEFINE_ASSOC_STRUCT. I succeeded to generate output with both of them, but they don't seem ideal: in vector you cannot access a member using a name (it is like a tuple) -- and in the other solution, I don't think I need both ways (member name and key type) to access the members.
#include <iostream>
#include <string>
#include <boost/spirit/include/karma.hpp>
#include <boost/fusion/include/map.hpp>
#include <boost/fusion/include/make_map.hpp>
#include <boost/fusion/include/vector.hpp>
#include <boost/fusion/include/as_vector.hpp>
#include <boost/fusion/include/transform.hpp>
struct sb_key;
struct id_key;
using boost::fusion::pair;
typedef boost::fusion::map
< pair<sb_key, int>
, pair<id_key, unsigned long>
> map_data;
typedef boost::fusion::vector < int, unsigned long > vector_data;
#include <boost/fusion/include/define_assoc_struct.hpp>
BOOST_FUSION_DEFINE_ASSOC_STRUCT(
(), assocstruct_data,
(int, a, sb_key)
(unsigned long, b, id_key))
namespace karma = boost::spirit::karma;
template <typename X>
std::string to_string ( const X& data )
{
std::string generated;
std::back_insert_iterator<std::string> sink(generated);
karma::generate_delimited ( sink, karma::int_ << karma::ulong_, karma::space, data );
return generated;
}
int main()
{
map_data d1(boost::fusion::make_map<sb_key, id_key>(234, 35314988526ul));
vector_data d2(boost::fusion::make_vector(234, 35314988526ul));
assocstruct_data d3(234,35314988526ul);
std::cout << "map_data as_vector: " << boost::fusion::as_vector(d1) << std::endl;
//std::cout << "map_data to_string: " << to_string(d1) << std::endl; //*FAIL No 1*
std::cout << "at_key (sb_key): " << boost::fusion::at_key<sb_key>(d1) << boost::fusion::at_c<0>(d1) << std::endl << std::endl;
std::cout << "vector_data: " << d2 << std::endl;
std::cout << "vector_data to_string: " << to_string(d2) << std::endl << std::endl;
std::cout << "assoc_struct as_vector: " << boost::fusion::as_vector(d3) << std::endl;
std::cout << "assoc_struct to_string: " << to_string(d3) << std::endl;
std::cout << "at_key (sb_key): " << boost::fusion::at_key<sb_key>(d3) << d3.a << boost::fusion::at_c<0>(d3) << std::endl;
return 0;
}
Including the commented line gives lots of pages of compilation errors, among which notably something like:
no known conversion for argument 1 from ‘boost::fusion::pair’ to ‘double’
no known conversion for argument 1 from ‘boost::fusion::pair’ to ‘float’
Might it be that to_string needs the values of the map_data, and not the pairs? Though I am not good with templates, I tried to get a vector from a map using transform in the following way
template <typename P>
struct take_second
{
typename P::second_type operator() (P p)
{
return p.second;
}
};
// ... inside main()
pair <char, int> ff(32);
std::cout << "take_second (expect 32): "
<< take_second<pair<char,int>>()(ff) << std::endl;
std::cout << "transform map_data and to_string: "
<< to_string(boost::fusion::transform(d1, take_second<>())); //*FAIL No 2*
But I don't know what types am I supposed to give when instantiating take_second and anyway I think there must be an easier way to get (iterate over) the values of a map (is there?)
If you answer this question, please also give your opinion on whether using an ASSOC_STRUCT or a map is better.
I think I noticed your question on the [spirit-general] list earlier.
It got 14 views there - and I did some fairly deep investigation. Sadly, to the best of my knowledge I don't think Spirit has any support for associate Fusion structures.
In fact, outside MSM and Phoenix, there was no place in boost where I see fusion::map being used.
Is there a chance you could just use std::map/std::pair instead? Here's a tiny proof of concept:
#include <boost/spirit/include/karma.hpp>
#include <boost/fusion/adapted.hpp>
int main()
{
const auto data = std::map<std::string, double> {
{ "pi", 3.1415925 },
{ "e", 2.718281828 },
{ "Answer", 42 } };
namespace karma = boost::spirit::karma;
std::cout << karma::format((karma::string << " = " << karma::double_) % karma::eol, data)
<< std::endl;
}
Output:
Answer = 42.0
e = 2.718
pi = 3.142