Leetcode May Challenge : Check If It Is a Straight Line - c++

Here is my code for the problem : Check If It Is a Straight Line
bool checkStraightLine(vector<vector<int>>& a) {
double m = (((double)a[1][1]-a[0][1])/(a[1][0]-a[0][0]));
for(int i=1;i<a.size()-1;i++)
{
double slope=(((double)a[i][1]-a[i+1][1])/(a[i][0]-a[i+1][0]));
if( m!=slope)
return false;
}
return true;
}
My doubt is why does my code produce an error when I replace :
double m = (((double)a[1][1]-a[0][1])/(a[1][0]-a[0][0]));
with
double m = (double)((a[1][1]-a[0][1])/(a[1][0]-a[0][0]));
and
double slope=(((double)a[i][1]-a[i+1][1])/(a[i][0]-a[i+1][0]));
with
double slope=(double)((a[i][1]-a[i+1][1])/(a[i][0]-a[i+1][0]));

Given:
int a = 1 , b = 2;
this line of code:
double d = (double)(a/b); // d is 0.
is not the same as:
double d = ((double)a/b); // d is 0.5
In the first case, you are doing an integer division before converting the result.
In the second case, you are converting the numerator to a double, and then dividing, which does a floating point division.
In your case, the error might be coming about because the code expects a non-zero slope, but the integer division gives you a zero.
Note that this comparison:
if( m!=slope)
is fundamentally flawed. You should never compare floating point numbers for equality. Use a threshold for the comparison instead.

Related

What does the int*. syntax do?

I am a newbie in C++ and this question will be probably so easy to answer for you. I can't find the actual meaning of this kind of syntax. So I have:
struct Vec {
double x, y, z;
Vec(double x_=0, double y_=0, double z_=0){ x=x_; y=y_; z=z_; }
};
int w = 1024, h = 768;
Vec cx = Vec(w*.5135/h);
What is happening in the last row? I am creating a new struct of type Vec and, what else ?
Thanks in advance.
It's a short way of writing floating point numbers. You can do that both ways(it has to be either a double of float of course). A decimal number is divided in 3 parts (excluding the sign that is):
123 . 456
| | \_fractional part
| |
| \_decimal point
|
integer part
When the integer part is equal to 0 but the fractional part is not:
double x = .123; // the same as writing 0.123
When the fractional part is equal to 0 but the integer part is not:
double x = 123.; // the same as writing 123.0
The * is just your standard multiplication here. You are just multiplying an integer number w with a decimal number .5135 that has its integer part equal to 0.
it is equivalent to:
Vec cx = Vec(w*0.5135/h);
In the last row you're assignming cx with a newly constructor instance of type Vec by calling it's constructor Vec(double x_=0, double y_=0, double z_=0).
Vec cx = Vec(w*.5135/h);
Is the same as:
Vec cx = Vec(w*0.5135/h, 0, 0);
Because of the default values for the parameters defined by the constructor.
An floating point number doesn't have to start with a 0 in C++.
assert(0.5135 == .5135); // True
So w*.5135 is just a multiplication of integer w and double 0.5135.

Make sure c++ decimal comparison is correct

I have two double variable. double a = 0.10000, double b = 0.1. How can I make sure the comparison (a == b) is always true ?
If you are being paranoid about using == on doubles or floats (which you should be) you can always check that they are close within a small tolerance.
bool same = fabs(a-b) < 0.000001;
The other answers here require you to scale the tolerance factor manually, which I wouldn't advise. For instance if you are comparing two numbers less than one millionth, one answer will always say the two numbers are "close enough." The other answer instead leaves it to the caller to specify which is equally error-prone.
I would instead suggest something like the following function. It will return 0 if the two doubles are within the stated range of each other, otherwise -1 (if d1 is smaller), or +1. Using fabs() may require you to link with the math library, such as with -lm.
#include <algorithm> // for max()
#include <cmath> // for fabs()
int double_compare( double d1, double d2 ) {
double dEpsilon = .00000001;
double dLarger = std::max( std::fabs(d1), std::fabs(d2) );
double dRange = dLarger * dEpsilon;
if ( std::fabs( d1 - d2 ) < dRange )
return 0;
return d1 < d2 ? -1: 1;
}
New answer to old question, but using epsilons is the way to go, check this example:
bool equals(const double a, const double b, const double maxRelativDiff = numeric_limits<double>::epsilon()) {
double difference = fabs(a - b);
const auto absoluteA = fabs(a);
const auto absoluteB = fabs(b);
double biggerBoi = (absoluteB > absoluteA) ? absoluteB : absoluteA; // Get the bigger number
return difference <= (biggerBoi * maxRelativDiff);
}
In this case you're checking if they are equal up to maxRelativDiff, so 0.0001 == 0.0001.
Check: https://en.cppreference.com/w/cpp/types/numeric_limits/epsilon

Value inside loop doesnt change in C++

here is a sample code that doesnt seem to work. I get the same value of X and Y ( both of them equal to zero ) for all the iteration. Can someone help me with this mistake of mine?
#include <iostream>
using namespace std;
int main()
{
double coord[4][2];
int div_x, div_y;
coord[1][0]=2;
coord[1][1]=0;
coord[2][0]=2;
coord[2][1]=4;
coord[3][0]=0;
coord[3][1]=4;
div_x = 4;
div_y = 3;
double a =0,b=0,c=0,d=0,e=0,f=0,g=0,h=0;
a = coord[1][0]+coord[2][0]+coord[3][0];
b = coord[1][0]+coord[2][0]-coord[3][0];
c = coord[2][0]-coord[1][0]+coord[3][0];
d = coord[2][0]-coord[1][0]-coord[3][0];
e = coord[1][1]+coord[2][1]+coord[3][1];
f = coord[1][1]+coord[2][1]-coord[3][1];
g = coord[2][1]-coord[1][1]+coord[3][1];
h = coord[2][1]-coord[1][1]-coord[3][1];
for (int i=0; i<div_y+1; i++){ // loop all rows (blue)
for (int j=0; j<div_x+1; j++){ // loop all nodes of one row (green)
double w = -1 + (2/div_x)*j;
double s = -1 + (2/div_y)*i;
double X = (a+b*w+c*s+(w*s*d));
double Y = (e+f*w+g*s+(h*s*w));
cout<<"\nX "<<X<<endl;
cout<<"\nY "<<Y<<endl;
}
}
return 0;
}
.
Your problem is with the divisions here:
double w = -1 + (2/div_x)*j;
double s = -1 + (2/div_y)*i;
2/div_x and 2/div_y are integer divisions. When you divide two values of type integer in C++, the division is carried out as an integer division. Since div_x is 4 and div_y is 3, the result of both of them is 0. As an integer division:
2 / 4 = 0
2 / 3 = 0
The easiest way to fix this is to use a double value for one of the two values, which results in a double division. For example:
double w = -1.0 + (2.0/div_x)*j;
double s = -1.0 + (2.0/div_y)*i;
You may also want to consider using the float type instead of double, unless you really need more than float precision, which is about 7 decimal digits.
In your code, div_x and div_y are int, thus, (2/div_x) and (2/div_y) are integer divisions, and evaluate to 0.
So w and s are both always equal to -1.
You can force float evaluation by using : (2.0/div_x) and (2.0/div_y)

C++ How do I set the fractional part of a float?

I know how to get the fractional part of a float but I don't know how to set it. I have two integers returned by a function, one holds the integer and the other holds the fractional part.
For example:
int a = 12;
int b = 2; // This can never be 02, 03 etc
float c;
How do I get c to become 12.2? I know I could add something like (float)b \ 10 but then what if b is >= than 10? Then I would have to divide by 100, and so on. Is there a function or something where I can do setfractional(c, b)?
Thanks
edit: The more I think about this problem the more I realize how illogical it is. if b == 1 then it would be 12.1 but if b == 10 it would also be 12.1 so I don't know how I'm going to handle this. I'm guessing the function never returns a number >= 10 for fractional but I don't know.
Something like:
float IntFrac(int integer, int frac)
{
float integer2 = integer;
float frac2 = frac;
float log10 = log10f(frac2 + 1.0f);
float ceil = ceilf(log10);
float pow = powf(10.0f, -ceil);
float res = abs(integer);
res += frac2 * pow;
if (integer < 0)
{
res = -res;
}
return res;
}
Ideone: http://ideone.com/iwG8UO
It's like saying: log10(98 + 1) = log10(99) = 1.995, ceilf(1.995) = 2, powf(10, -2) = 0.01, 99 * 0.01 = 0.99, and then 12 + 0.99 = 12.99 and then we check for the sign.
And let's hope the vagaries of IEEE 754 float math won't hit too hard :-)
I'll add that it would be probably better to use double instead of float. Other than 3d graphics, there are very few fields were using float is a good idea nowadays.
The most trivial method would be counting the digits of b and then divide accordingly:
int i = 10;
while(b > i) // rather slow, there are faster ways
i*= 10;
c = a + static_cast<float>(b)/i;
Note that due to the nature of float the result might not be what you expected. Also, if you want something like 3.004 you can modify the initial value of i to another power of ten.
kindly try this below code after including include math.h and stdlib.h file:
int a=12;
int b=22;
int d=b;
int i=0;
float c;
while(d>0)
{
d/=10;
i++;
}
c=a+(float)b/pow(10,i);

Double in object method not accepting fractional values?

I am having trouble with a C++ object-orientated script. When I create an object, I wish to calculate an AttributeQ based on its attributes MyAValue, MyBValue, and MyCValue.
While using the Visual 2010 debugger, I noticed that TempAttribueQ seems to always be 0 (except before it is initialized of course). Assuming Delta != 0, BVal == Maximum, and DeltaA == DeltaC, then TempAttribueQ should be 1/3 not 0.
At first I thought it was a scope problem, but the variable is defined outside the if-else statements. I have tried initializing TempAttribueQ as some outrageous number, which it keeps up until the if-else statements when it becomes 0 when it shouldn't.
This is my code...
void SetMyAttribueQ(){
double TempAVal = MyAValue;
double TempBVal = MyBValue;
double TempCVal = MyCValue;
double Minimum = min(min(TempAVal, TempBVal), TempCVal);
double Maximum = max(max(TempAVal, TempBVal), TempCVal);
double Delta = Maximum - Minimum;
double DeltaA = 0;
double DeltaB = 0;
double DeltaC = 0;
double TempAttribueQ = 0;
if(Delta == 0) {
MyAttribueQ = TempAttribueQ; // this->SetMyAttribueQ(TempAttribueQ);
}
else {
DeltaA = /* (a removed equation goes here... */
DeltaB = /* (a removed equation goes here... */
DeltaC = /* (a removed equation goes here... */
if(AVal == Maximum)
TempAttribueQ = (DeltaC - DeltaB);
else if(BVal == Maximum)
TempAttribueQ = (1/3) + (DeltaA - DeltaC);
else
TempAttribueQ = (2/3) + (DeltaB - DeltaA);
MyAttribueQ = TempAttribueQ;
}
}
What is preventing TempAttribueQ from getting a value of 1/3 or 2/3? Or, what is causing it to be set to be set to 0?
When you divide one integer by another, you get an integer result. Change either or both the constants to non-integer to fix it - C++ rules will result in the other being converted to floating point before the division takes place. All of the following will work:
1.0 / 3.0
1 / 3.0
1.0 / 3
An integer will get converted back to a double invisibly, which is why you weren't seeing any errors in your code.
1 is an integer and 3 is an integer so 1/3 uses integer arithmetic.
You want to use 1.0/3.0 to force double precision arithmetic.
1/3 == 0 due to integer division, which is set to TempAttribueQ.
You need to do 1./3 which will produce 0.3333333..
Try 1.0/3.0 and 2.0/3.0. 1/3 and 2/3 are 0 due to integer division.