is there an EIGEN equivalent for gsl_matrix_isnull? - c++

Is there a function in Eigen for testing whether a matrix vanishes? Like gsl_matrix_isnull in GSL? I have searched for quite a while, but found nothing such.
If not, is there anything faster than straightforwardly checking each element?
Thank you and sorry if I overlooked it.

I don't think that there is an exact equivalent, but there are multiple ways of an equivalent expression. Consider the following:
Eigen::MatrixXd mt(4, 4);
std::cout << mt << "\n";
std::cout << mt.array().isApproxToConstant(0.0, 1e-15) << "\n";
mt *= 0.;
std::cout << (mt.array().abs() < 1e-15).all() << "\n";
std::cout << mt.array().isApproxToConstant(0.0, 1e-15) << "\n";
std::cout << mt.array().cwiseEqual(0.0).all() << "\n";
The isApproxToConstant compares all the elements to the first argument with a precision of the second. (mt.array().abs() < 1e-15).all() checks the same, but has to be near zero. If you want exactly 0, then use mt.array().cwiseEqual(0.0).all().

To complete Avi's answer, there is isZero(eps) which is essentially a shortcut to (mat.array().abs()<=eps).all(), for instance:
if(mat.isZero()) { ... }

Related

How to convert double to string with precision for total number of digits(both left and right side of the decimal)?

I am looking for a way to convert double to string in c++ such that total number of digits remain to be 10 irrespective of how many are present before and after the decimal point and irrespective of the zeroes. Examples for better understanding:
0.00000000000000000000 =expected outcome> 0.0000000000
12345.00000000000000000 =expected outcome> 12345.00000
-15.123456789012 =expected outcome> -15.12345678
I couldnt find any relevant answer. For the methods like snprintf, std::setprecision with ostringstream, to_string, Boost's lexical_cast, some of the above case fails.
Example of code:
double num = 12345.0000000000001;
std::ostringstream streamObj2;
streamObj2 << std::fixed << std::setprecision(10) << num;
std::string strObj2 = streamObj2.str();
std::cout << strObj2 << '\n';
The output = 12345.0000000000, which is not what I am expecting. Removing std::fixed gives output as 12345
What I require = 12345.00000
Please help me, thanks.
Thanks for the comments, because of which I found the answer. Using std::showpoint instead of std::fixed helped fulfill the requirement.
double num = 12345.0000000000001;
std::ostringstream streamObj2;
streamObj2 << std::showpoint << std::setprecision(10) << num;
std::string strObj2 = streamObj2.str();
std::cout << strObj2 << '\n';
Output: 12345.00000

getting wrong answer by logarithm in c++

Well i was creating a program in c++ .Then i noticed that there were some error due to which my program was not functioning correctly
compiler used:- Dev c++
Error was this:-
Suppose n1=274877906944 which is 2^38. so log(n1) should be 38 which is correct. now let n2=274877906942 which is smaller than n1.
So that means if we calculate log(n2) then it must give me less than log(n1).But log(n2) gave me the same result as log(n1) which is 38.
Which is wrong!!!
Someone please explain this stuff..
You see the result that you do because of rounding. If you increase your precision, it'll be okay (note that the log2 function in <cmath> will cast your integers to double):
std::cout << std::fixed;
std::cout << std::setprecision(16);
std::cout << static_cast<double>(274877906944) << std::endl;
std::cout << static_cast<double>(274877906942) << std::endl;
std::cout << static_cast<double>(274877906948) << std::endl;
std::cout << log2(274877906944) << std::endl;
std::cout << log2(274877906942) << std::endl;
std::cout<< log2(274877906948) << std::endl;
Produces:
274877906944.0000000000000000
274877906942.0000000000000000
274877906948.0000000000000000
38.0000000000000000
37.9999999999895053
38.0000000000209965
Demo

Setting precision of floating point number

Hello guys I am new in C++
I am trying to write the function to calculate the second moment of inertia and set the precision with 3 decimal places.
In the output does not apply the 3 decimal places in the first call but the following 4 calls does applied. Here is my codes , please help me find the error and if possible please explain some details thank you very much !
double beamMoment(double b, double h) //the function that calculating the second moment of inertia
{
double I; //variables b=base, h=height, I= second moment of inertia
I = b * (pow(h, 3.0) / 12); // formular of the second momeent of inertia
ofs << "b=" << b << "," << "h=" << h << "," << "I=" << I << setprecision(3) << fixed << endl;
ofs << endl;
return I;
}
int main()
{
beamMoment(10,100);
beamMoment(33, 66);
beamMoment(44, 88);
beamMoment(26, 51);
beamMoment(7, 19);
system("pause");
return 0;
}
The output in my text file is as follow :
b=10,h=100,I=833333
b=33.000,h=66.000,I=790614.000
b=44.000,h=88.000,I=2498730.667
b=26.000,h=51.000,I=287410.500
b=7.000,h=19.000,I=4001.083
You have to set stream precision before printing a number.
ofs << 5.5555 << setprecision(3) << endl; // prints "5.5555"
ofs << setprecision(3) << 5.5555 << endl; // prints "5.555"
Stream operators << and >> are, in fact, methods that can be chained. Let's say we have a piece of example java code like:
dog.walk().stopByTheTree().pee();
In C++, if we'd use stream operators, it'd look like:
dog << walk << stopByTheTree << pee;
Operations on dog objects are executed from left to right, and the direction of "arrows" doesn't matter. These method names are just syntactic sugar.
Look here for more details.

first setw with double is left aligned, subsequent are right aligned

I was trying to affirm my knowledge about how streams work with doubles and various manipulators, and stumbled upon G++ doing something strange:
int main() {
double v = 10.0/3.;
//std::cout << v << '\n';
std::cout << std::setw(5) << std::setprecision(2) << v << '\n';
std::cout << std::setw(5) << std::setprecision(2) << std::fixed << v << '\n';
}
Output:
3.3 //why is this left aligned?
3.33 //why is this right aligned? which is right?
See it live here
Then I uncommented that first cout and got different results!
3.33333 //which alignment is this?
3.3 //now this is right aligned?!
3.33 //that implies right-aligned is correct
Subsequent tests show that the first double I stream out is left aligned, and all subsequent doubles are right aligned:
double v = 10.0/3.;
std::cout << std::setw(10) << v << '\n';
std::cout << std::setw(5) << std::setprecision(2) << std::fixed << v << '\n';
std::cout << std::setw(5) << std::setprecision(2) << v << '\n';
std::cout << std::setw(5) << std::setprecision(2) << v << '\n';
Output:
3.33333 //well, this is left aligned
3.33
3.3
3.3 //all subsequent tests are right aligned
Clang++ on Coliru is doing the same thing, I presume because they're using the same library.
I know the answer to "is this a G++ bug" is no 99.9% of the time, so can someone potentially explain the behavior I'm seeing?
After running this on other IDEs I would conclude that this is a problem not with g++/clang++, nor is any standard behavior, but a problem with the Coliru editor itself. I ran this on several different sites including Rextester and Ideone and I got the correct output for all of them. This seems to be a problem only belonging to the Coliru editor.
Streams are, by default, right-justified. When setting the width using std::setw(), the stream will insert padding characters as specified by out.fill() into the beginning (or end) of the output stream. I've noticed that Coliru doesn't add any padding characters on the first output operation when the stream is using the default fill character (a simple space). But when I change the fill character to anything other than a space, it works just fine.

std::cout << Predicting the automatic field width in displayed for an arbitrary double

I'm displaying a large number of doubles on the console, and I would like to know in advance how many decimal places std::cout will decide to display for a given double. This is basically so I can make it look pretty in the console.
e.g. (pseudo-code)
feild_width = find_maximum_display_precision_that_cout_will_use( whole_set_of_doubles );
...
// Every cout statement:
std::cout << std::setw( feild_width ) << double_from_the_set << std::endl;
I figure cout "guesses"? a good precision to display based on the double. For example, it seems to display
std::cout << sqrt(2) << std::endl;
as 1.41421, but also
std::cout << (sqrt(0.5)*sqrt(0.5) + sqrt(1.5)*sqrt(1.5)) << std::endl;
as 2 (rather than 2.000000000000?????? or 1.99999999?????). Well, maybe this calculates to exactly 2.0, but I don't think that sqrt(2) will calculate to exactly 1.41421, so std::cout has to make some decision about how many decimal places to display at some point, right?
Anyway possible to predict this to formulate a find_maximum_display_precision...() function?
What you need is the fixed iomanip.
http://www.cplusplus.com/reference/iostream/manipulators/fixed/
double d = 10/3;
std::cout << std::setprecision(5) << std::fixed << d << std::endl;
Sometimes C++ I/O bites. Making pretty output is one of those sometimes. The C printf family is easier to control, more understandable, more terse, and isn't plagued with those truly awful ios:: global variables. If you need to use C++ output for other reasons, you can always sprintf/snprintf to a string buffer and then print that using the << to stream operator. IMHO, If you don't need to use C++ output, don't. It is ugly and verbose.
In your question you are mixing precision and width, which are two different things.
Other answers concentrate on precision, but the given precision is the maximum, not a minimum of displayed digits. It does not pad trailing zeros, if not ios::fixed or ios::scientific is set.
Here is a solution to determine the number of characters used for output, including sign and powers of 10:
#include <string>
#include <sstream>
#include <vector>
size_t max_width(const std::vector<double>& v)
{
size_t max = 0;
for (size_t i = 0; i < v.size(); ++i)
{
std::ostringstream out;
// optional: set precision, width, etc. to the same as in std::cout
out << v[i];
size_t length = out.str().size();
if (length > max) max = length;
}
return max;
}
std::cout::precision(); use it to determine precision
example :
# include <iostream>
# include <iomanip>
int main (void)
{
double x = 3.1415927
std::cout << "Pi is " << std::setprecision(4) << x << std::endl;
return 1;
}
This would display:
Pi is 3.142
This link also includes explanation for std::cout::precision();
http://www.cplusplus.com/reference/iostream/ios_base/precision/