JavaScript:
var lon2 = (lon1.toRad()+L+3*Math.PI)%(2*Math.PI) - Math.PI;
I have converted to c++:
double lon2 = (Deg2Rad(lon1)+L+3*PI)%(2*PI) - PI;
Note: Deg2Rad func returns double, PI is a double also, L and lon1 also double. Then I got the following errors for the same line:
error C2296: '%' : illegal, left operand has type 'double'
error C2297: '%' : illegal, right operand has type 'double'
Whats wrong with this % modulo?
the modulo operator is not defined for floats and doubles (only integer types), use fmod instead (or consider changing how you perform your calculation).
C++ will not perform a modulo operation on a double - I suggest using fmod() in <math.h>
If you wanted to be very fancy about it, you could overload the modulo (%) operator to handle your desired datatypes.
% is defined for integers only. Use the fmod() function in <cmath> to calculate the modulus of a floating point number (float or double).
Related
I'm very familiar with c++ but today I notice something,
float a=(float)5/2; //this gives 2.5, its okay
float b=(float)(5/2); //this gives 2, why?
Please can you name this topic and any answer will help me.
In this expression in parentheses (5/2) there is used the integer arithmetic. The result of the expression is 2.
In this expression (float)5/2 there is used the floating arithmetic because one of the operands has the type float after its explicit casting (float)5.. The unary casting operator has a higher priority than the division operator /.
You could write equivalently
5.f/2
This is an issue with operator precedence. When you write
(float)5/2
it’s interpreted as
((float) 5) / 2
which means “treat 5 as a float, then divide it by the integer 2.” Therefore, the division is done as floating-point division.
When you write
(float)(5/2)
you’re saying “divide the integer 5 by the integer 2, then treat that as a float.” The division done is therefore integer division, which rounds down, so you get 2 as your result.
I don't understand how a typecast can sit at the beginning of a binary arithmetic expression. Does it typecast both variables or only one?
#include <stdio.h>
main()
{
int sum = 17, count = 5;
double mean = (double) sum / count;
printf("Value of mean : %f\n", mean );
}
Is it casting (double) (sum / count) or only ((double) sum) / count?
It is parsed as ((double) sum) / count. Casting one of the operands is a common trick to force floating-point division. int / int would use integral division which truncates the decimal portion. double / int forces the second operand to be coerced into a double as well, resulting in double / double which doesn't truncate.
Notice that if it were parsed as (double) (sum / count) it would not work. This would still perform integer division, truncate the decimal portion, and then cast that result to a double. The cast would come too late.
When in doubt, consult cppreference.com. Their operator precedence chart shows that C-style casts have higher precedence than division:
The following table lists the precedence and associativity of C++ operators. Operators are listed top to bottom, in descending precedence.
The typecast operator has higher precedence than the division operator. So this:
(double) sum / count
Parses as this:
((double) sum) / count
Meaning that sum is typecast to a double. Then, because one operand to / has type double and the other has type int, The int operand is converted to double as per the usual arithmetic conversions and floating point division is performed.
I have a long double sine and a long long int amp. I am using <cmath> and have code as follows:
sine = sin(point);
amp = round(sine * 2^31);
Here the variable point is incrementing in 0.009375 intervals. The first line here works fine but on the second I receive this error message:
error: invalid operands of types 'long double' and 'int' to binary 'operator^'
I'm unsure what this error means and the main request here is 'How can I get around this to get an output integer into the variable amp?'
In C++ the ^ operator means exclusive or, not exponentiation. You probably meant (1ULL << 31).
The reason for the error is that * is multiplication, and ^ is the bitwise xor operator which can only be applied to integral types.
Multiplication (*) has higher precedence than ^. So the compiler interprets amp = round(sine * 2^31); as amp = round( (sine *2)^31);. sine (presumably) has type long double, so the result of sine*2 is also of type long double. long double is not an integral type, so cannot be an operand of ^. Hence the error.
Your mistake is assuming that ^ represents exponentiation, which it does not.
You can fix the problem by either
amp = round (sine * pow(2.0, 31)); // all floating point
or
amp = round (sine * (1UL << 31));
The second computes 1 leftshifted 31 bits as an unsigned long (which is guaranteed able to represeny the result, unlike unsigned or int for which there is not such a guarantee). Then, in doing the multiplication, it promotes that value to long double.
If you are doing predominantly floating point operations, the first is more understandable to people who will maintain such code. The second is probably rather cryptic to someone who writes numeric code but is not well acquainted with bit fiddling operations - as, ironically, you have demonstrated in your belief that ^ is exponentiation.
You would need to test to determine which option offers greater performance (given the need to convert unsigned long to long double in the second , and potential for std::pow() in the first to be optimised for some special cases). In other words, there is potential for the compiler optimiser to get aggressive in both cases, or for the implementation of pow() to be lovingly hand-crafted, or both.
a complete newbie here. For my school homework, I was given to write a program that displays -
s= 1 + 1/2 + 1/3 + 1/4 ..... + 1/n
Here's what I did -
#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
int a;
float s=0, n;
cin>>a;
for(n=1;n<=a;n++)
{
s+=1/n;
}
cout<<s;
getch();
}
It perfectly displays what it should. However, in the past I have only written programs which uses int data type. To my understanding, int data type does not contain any decimal place whereas float does. So I don't know much about float yet. Later that night, I was watching some video on YouTube in which he was writing the exact same program but in a little different way. The video was in some foreign language so I couldn't understand it. What he did was declared 'n' as an integer.
int a, n;
float s=0;
instead of
int a
float s=0, n;
But this was not displaying the desired result. So he went ahead and showed two ways to correct it. He made changes in the for loop body -
s+=1.0f/n;
and
s+=1/(float)n;
To my understanding, he declared 'n' a float data type later in the program(Am I right?). So, my question is, both display the same result but is there any difference between the two? As we are declaring 'n' a float, why he has written 1.0f instead of n.f or f.n. I tried it but it gives error. And in the second method, why we can't write 1(float)/n instead of 1/(float)n? As in the first method we have added float suffix with 1. Also, is there a difference between 1.f and 1.0f?
I tried to google my question but couldn't find any answer. Also, another confusion that came to my mind after a few hours is - Why are we even declaring 'n' a float? As per the program, the sum should come out as a real number. So, shouldn't we declare only 's' a float. The more I think the more I confuse my brain. Please help!
Thank You.
The reason is that integer division behaves different than floating point division.
4 / 3 gives you the integer 1. 10 / 3 gives you the integer 3.
However, 4.0f / 3 gives you the float 1.3333..., 10.0f / 3 gives you the float 3.3333...
So if you have:
float f = 4 / 3;
4 / 3 will give you the integer 1, which will then be stored into the float f as 1.0f.
You instead have to make sure either the divisor or the dividend is a float:
float f = 4.0f / 3;
float f = 4 / 3.0f;
If you have two integer variables, then you have to convert one of them to a float first:
int a = ..., b = ...;
float f = (float)a / b;
float f = a / (float)b;
The first is equivalent to something like:
float tmp = a;
float f = tmp / b;
Since n will only ever have an integer value, it makes sense to define it as as int. However doing so means that this won't work as you might expect:
s+=1/n;
In the division operation both operands are integer types, so it performs integer division which means it takes the integer part of the result and throws away any fractional component. So 1/2 would evaluate to 0 because dividing 1 by 2 results in 0.5, and throwing away the fraction results in 0.
This in contrast to floating point division which keeps the fractional component. C will perform floating point division if either operand is a floating point type.
In the case of the above expression, we can force floating point division by performing a typecast on either operand:
s += (float)1/n
Or:
s += 1/(float)n
You can also specify the constant 1 as a floating point constant by giving a decimal component:
s += 1.0/n
Or appending the f suffix:
s += 1.0f/n
The f suffix (as well as the U, L, and LL suffixes) can only be applied to numerical constants, not variables.
What he is doing is something called casting. I'm sure your school will mention it in new lectures. Basically n is set as an integer for the entire program. But since integer and double are similar (both are numbers), the c/c++ language allows you to use them as either as long as you tell the compiler what you want to use it as. You do this by adding parenthesis and the data type ie
(float) n
he declared 'n' a float data type later in the program(Am I right?)
No, he defined (thereby also declared) n an int and later he explicitly converted (casted) it into a float. Both are very different.
both display the same result but is there any difference between the two?
Nope. They're the same in this context. When an arithmetic operator has int and float operands, the former is implicitly converted into the latter and thereby the result will also be a float. He's just shown you two ways to do it. When both the operands are integers, you'd get an integer value as a result which may be incorrect, when proper mathematical division would give you a non-integer quotient. To avoid this, usually one of the operands are made into a floating-point number so that the actual result is closer to the expected result.
why he has written 1.0f instead of n.f or f.n. I tried it but it gives error. [...] Also, is there a difference between 1.f and 1.0f?
This is because the language syntax is defined thus. When you're declaring a floating-point literal, the suffix is to use .f. So 5 would be an int while 5.0f or 5.f is a float; there's no difference when you omit any trailing 0s. However, n.f is syntax error since n is a identifier (variable) name and not a constant number literal.
And in the second method, why we can't write 1(float)/n instead of 1/(float)n?
(float)n is a valid, C-style casting of the int variable n, while 1(float) is just syntax error.
s+=1.0f/n;
and
s+=1/(float)n;
... So, my question is, both display the same result but is there any difference between the two?
Yes.
In both C and C++, when a calculation involves expressions of different types, one or more of those expressions will be "promoted" to the type with greater precision or range. So if you have an expression with signed and unsigned operands, the signed operand will be "promoted" to unsigned. If you have an expression with float and double operands, the float operand will be promoted to double.
Remember that division with two integer operands gives an integer result - 1/2 yields 0, not 0.5. To get a floating point result, at least one of the operands must have a floating point type.
In the case of 1.0f/n, the expression 1.0f has type float1, so the n will be "promoted" from type int to type float.
In the case of 1/(float) n, the expression n is being explicitly cast to type float, so the expression 1 is promoted from type int to float.
Nitpicks:
Unless your compiler documentation explicitly lists void main() as a legal signature for the main function, use int main() instead. From the online C++ standard:
3.6.1 Main function
...
2 An implementation shall not predefine the main function. This function shall not be overloaded. It shall have a declared return type of type int, but otherwise its type is implementation-defined...
Secondly, please format your code - it makes it easier for others to read and debug. Whitespace and indentation are your friends - use them.
1. The constant expression 1.0 with no suffix has type double. The f suffix tells the compiler to treat it as float. 1.0/n would result in a value of type double.
I have a line of code
double i = 1 + (long)1.5* 5.0f
My question is what is the conversion order and the result? Been searching for examples like this, but to no avail. Any good guides out there that may help me understand it?
My question is what is the conversion order and the result?
The cast is applied to 1.5, giving a long with value 1.
That's converted to float for multiplication with 5.0f, giving a float with value 5.0f.
1 is converted to float for addition with that value, giving a float with value 6.0f.
Finally, that's promoted to double (retaining the value 6.0) to assign to i.
This assumes a non-crazy floating point format that can represent small integers exactly; otherwise, there may be rounding errors.
If you wanted to cast the result of the multiplication, then use parentheses to control the operator precedence:
double i = 1 + (long)(1.5* 5.0f); // = 8.0
or use a C++-style cast, which forces the use of parentheses:
double i = 1 + static_cast<long>(1.5* 5.0f)
Any good guides out there that may help me understand it?
Here's one: http://en.cppreference.com/w/cpp/language/operator_precedence. Note that the type cast has a higher precedence than multiplication, which is in turn higher than addition (3 vs. 5 vs. 6).
As you can see from this table, the cast operator has higher precedence than multiplication, but follow the advice to use parentheses.
This precedence table should tell you everything you need to know.
Casting: 1.5 is cast to a long
Multiplication: 1.5 * 5.0f, which casts this product as a float
Addition: 1 + ( ((long) 1.5) * 5.0f)
Assignment: i = 1 + ((long) 1.5 * 5.0f)
If you're not sure what the precedence of the casting operator is then rewrite the expression (in your head)
(long)1.5 * 5.0
to
5.0 * (long)1.5
Here its pretty obvious what has precedence and its the same with the first version