i have an inexplicable problem. Here is my code:
int result;
result = 0 * 2 ^ 1;
std::cout << result << std::endl;
The result of this calculation is 1. But why? Actually it should be 0, shouldn't it?
I've tried it with the pow-function of the math-library but there the result also is 1:
int result;
result = std::pow(0 * 2, 1);
std::cout << result << std::endl;
In C++, and many other computer programming languages, ^ means XOR not power-of. So it may not have the precedence you expected from mathematics.
Use std::pow for exponents:
const int result = std::pow(0 * 2, 1);
std::cout << result << '\n';
Related
I’m writing a formula to solve for the roots of a quadratic in C++. My output should begin with the equation such as
3x^2 +2x -3
Everything in my program is correct except for this part. My output has all plus signs followed by the coefficient. How can I get it to display minus (-) signs instead of + when a coefficient is negative? Any help is appreciated thanks!
Example code:
std::cout << a << “x^2” << “+” << b<< “x”
If b is negative it prints ax^2 + -3x but I need it to display ax^2 - 3x
std::cout << a << "x^2" << b >= 0? "+" : "" << b<< "x";
Use ternary operator to make sure "+" is only there when b is not negative.
Your problem with something like:
std::cout << a << "x^2" << "+" << b << "x";
is that you are always outputting a + followed by the b value, be it positive or negative (or zero for that matter). Consider a = 7, b = -42:
7x^2+-42x
As you've seen, these won't look nice for negative numbers. You could get rid of the + but then it would look bad for positive numbers. Consider a = 7, b = 42:
7x^242x
The following code shows a slightly different approach, where the coefficients are checked for sign and then the output is adjusted properly. It also handles arbitrary powers, though only down to zero, allows you to decide whether to print zero coefficients or not, and spaces the terms nicely:
#include <iostream>
#include <vector>
void outputEquation(const std::vector<int> &vec, bool showZeros = false) {
// Power counts down, first is to change
// formatting of first term.
auto power = vec.size() - 1;
auto first = true;
// Handle each coefficient.
for (const auto coeff: vec) {
// Select whether zero coefficients are shown.
if (coeff != 0 || showZeros) {
// Leading space on all but first term.
if (! first) std::cout << " ";
// Intelligently handle negative/non-negative.
if (coeff >= 0) {
// No leading '+' on first term,
// only print coefficient if not 1.
if (! first) std::cout << "+ ";
if (coeff != 1) std::cout << coeff;
} else {
// Output sign for negative, with space after
// if not first term. Then output |coeff|
// unless 1.
std::cout << "-";
if (! first) std::cout << " ";
if (coeff != -1) std::cout << -coeff;
}
// Output power, taking into account "x^1"
// and "x^0", which become "x" and "".
if (power > 1) {
std::cout << "x^" << power;
} else if (power == 1) {
std::cout << "x";
}
// First term done, adjust future behaviour.
first = false;
}
// Decrease power for next element.
--power;
}
// If no terms were output, just give 0.
if (first) {
std::cout << '0';
}
std::cout << '\n';
}
void outputEquation(int a, int b, int c, bool showZeros = false) {
// Just make a vector and call function above.
outputEquation({a, b, c}, showZeros);
}
// Test harness, adapt as necessary.
int main() {
outputEquation({ -4, 3, -2, 1, -1, 0, 4 });
outputEquation({ });
outputEquation({ 4 });
outputEquation({ 0 });
outputEquation({ 0, 1, 2 });
outputEquation({ 0, 0, 0, 0, 99, 0, 0, 0, 0 });
outputEquation({ 0, 0, 0, 0, 99, 0, 0, 0, 0 }, true);
outputEquation(1, 2, 3);
}
The first overloaded function is a general purpose one which you can augment with the second overload, meant specifically for quadratics. This outputs:
-4x^6 + 3x^5 - 2x^4 + x^3 - x^2 + 4
0
4
0
x + 2
9x^4
0x^8 + 0x^7 + 0x^6 + 0x^5 + 99x^4 + 0x^3 + 0x^2 + 0x + 0
x^2 + 2x + 3
but you can adjust the parameters for other possibilities.
I need truncation of 2 decimal digits after decimal comma.
I am using following code in C++:
auto doubleTmp = value * 100.00;
int64_t tmp = static_cast<int64_t>(doubleTmp);
double res = ( static_cast<double>(tmp) ) /100.00;
but for example when I set value = 70.82 doubleTmp is 70.8199999 and result is 70.81. What will better way for this and why?
The problem is that neither the input value nor the result res is representable in a computer memory accurately for 70.82. As #MatthieuBrucher suggested, you should use std::lround; consider the following code:
auto value = 70.82;
std::cout << std::fixed << std::setprecision(20) << value << std::endl;
auto tmp = std::lround(value * 100.0);
std::cout << tmp << std::endl;
double res = static_cast<double>(tmp) / 100.00;
std::cout << std::fixed << std::setprecision(20) << res << std::endl;
Which gives the following output:
70.81999999999999317879
7082
70.81999999999999317879
However, you can store the result as a pair of integral numbers, where the first one will represent the integral part and the second one the fractional part:
auto res_integral = tmp / 100;
auto res_fractional = tmp % 100;
std::cout << res_integral << "." << res_fractional << std::endl;
Or, simply store it as tmp with the knowledge that you are storing 100*x instead of x.
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");
}
Out of nowhere I get quite a big result for this function... It should be very simple, but I can't see it now.
double prob_calculator_t::pimpl_t::B_full_term() const
{
double result = 0.0;
for (uint32_t j=0, j_end=U; j<j_end; j++)
{
uint32_t inhabited_columns = doc->row_sums[j];
// DEBUG
cout << "inhabited_columns: " << inhabited_columns << endl;
cout << "log_of_sum[j]: " << log_of_sum[j] << endl;
cout << "sum_of_log[j]: " << sum_of_log[j] << endl;
// end DEBUG
result += ( -inhabited_columns * log( log_of_sum[j] ) + sum_of_log[ j ] );
cout << "result: " << result << endl;
}
return result;
}
and where is the trace:
inhabited_columns: 1
log_of_sum[j]: 110.56
sum_of_log[j]: -2.81341
result: 2.02102e+10
inhabited_columns: 42
log_of_sum[j]: 110.56
sum_of_log[j]: -143.064
result: 4.04204e+10
Thanks for the help!
inhabited_columns is unsigned and I see a unary - just before it: -inhabited_columns.
(Note that unary - has a really high operator precedence; higher than * etc).
That is where your problem is! To quote Mike Seymour's answer:
When you negate it, the result is still unsigned; the value is reduced
modulo 232 to give a large positive value.
One fix would be to write
-(inhabited_columns * log(log_of_sum[j]))
as then the negation will be carried out in floating point
inhabited_columns is an unsigned type. When you negate it, the result is still unsigned; the value is reduced modulo 232 to give a large positive value.
You should change it to a sufficiently large signed type (maybe int32_t, if you're not going to have more than a couple of billion columns), or perhaps double since you're about to use it in double-precision arithmetic.
In matlab/octave pairwise distances between matrices as required for e.g. k-means are calculated by one function call (see cvKmeans.m), to distFunc(Codebook, X) with as arguments two matrices of dimensions KxD.
In Eigen this can be done for a matrix and one vector by using broadcasting, as explained on eigen.tuxfamily.org:
(m.colwise() - v).colwise().squaredNorm().minCoeff(&index);
However, in this case v is not just a vector, but a matrix. What's the equivalent oneliner in Eigen to calculate such pairwise (Euclidean) distances across all entries between two matrices?
I think the appropriate solution is to abstract this functionality into a function. That function may well be templated; and it may well use a loop - the loop will be really short, after all. Many matrix operations are implemented using loops - that's not a problem.
For example, given your example of...
MatrixXd p0(2, 4);
p0 <<
1, 23, 6, 9,
3, 11, 7, 2;
MatrixXd p1(2, 2);
p1 <<
2, 20,
3, 10;
then we can construct a matrix D such that D(i,j) = |p0(i) - p1(j)|2
MatrixXd D(p0.cols(), p0.rows());
for (int i = 0; i < p1.cols(); i++)
D.col(i) = (p0.colwise() - p1.col(i)).colwise().squaredNorm().transpose();
I think this is fine - we can use some broadcasting to avoid 2 levels of nesting: we iterate over p1's points, but not over p0's points, nor over their dimensions.
However, you can make a oneliner if you observe that |p0(i) - p1(j)|2 = |p0(i)|2 + |p1(j)|2 - 2 p0(i)T p1(j). In particular, the last component is just matrix multiplication, so D = -2 p0T p1 + ...
The blank left to be filled is composed of a component that only depends on the row; and a component that only depends on the column: these can be expressed using rowwise and columnwise operations.
The final "oneliner" is then:
D = ( (p0.transpose() * p1 * -2
).colwise() + p0.colwise().squaredNorm().transpose()
).rowwise() + p1.colwise().squaredNorm();
You could also replace the rowwise/colwise trickery with an (outer) product with a 1 vector.
Both methods result in the following (squared) distances:
1 410
505 10
32 205
50 185
You'd have to benchmark which is fastest, but I wouldn't be surprised to see the loop win, and I expect that's more readable too.
Eigen is more of a headache than I thought on first sight.
There is no reshape() functionality for example (and conservativeResize is something else).
It also seems (I'd like to be corrected) to be the case that Map does not just offer a view on the data, but assignments to temporary variables seem to be required.
The minCoeff function after the colwise operator cannot return a minimum element and an index to that element.
It is unclear to me if replicate is actually allocating duplicates of the data. The reason behind broadcasting is that this is not required.
matrix_t data(2,4);
matrix_t means(2,2);
// data points
data << 1, 23, 6, 9,
3, 11, 7, 2;
// means
means << 2, 20,
3, 10;
std::cout << "Data: " << std::endl;
std::cout << data.replicate(2,1) << std::endl;
column_vector_t temp1(4);
temp1 = Eigen::Map<column_vector_t>(means.data(),4);
std::cout << "Means: " << std::endl;
std::cout << temp1.replicate(1,4) << std::endl;
matrix_t temp2(4,4);
temp2 = (data.replicate(2,1) - temp1.replicate(1,4));
std::cout << "Differences: " << std::endl;
std::cout << temp2 << std::endl;
matrix_t temp3(2,8);
temp3 = Eigen::Map<matrix_t>(temp2.data(),2,8);
std::cout << "Remap to 2xF: " << std::endl;
std::cout << temp3 << std::endl;
matrix_t temp4(1,8);
temp4 = temp3.colwise().squaredNorm();
std::cout << "Squared norm: " << std::endl;
std::cout << temp4 << std::endl;//.minCoeff(&index);
matrix_t temp5(2,4);
temp5 = Eigen::Map<matrix_t>(temp4.data(),2,4);
std::cout << "Squared norm result, the distances: " << std::endl;
std::cout << temp5.transpose() << std::endl;
//matrix_t::Index x, y;
std::cout << "Cannot get the indices: " << std::endl;
std::cout << temp5.transpose().colwise().minCoeff() << std::endl; // .minCoeff(&x,&y);
This is not a nice oneliner and seems overkill just to compare every column in data with every column in means and return a matrix with their differences. However, the versatility of Eigen does not seem to be such that this can be written down much shorter.