Let's say I have an unsigned number:
unsigned foo = 2;
When I try to inverse it and print it, I get an output of 0:
Serial.println(1/foo);
Shouldn't I recieve 0.5 (1/2)?
Thanks!
Let's say I have an unsigned number:
unsigned foo = 2;
When I try to inverse it and print it, I get an output of 0:
Serial.println(1/foo);
Shouldn't I recieve 0.5 (1/2)?
Thanks!
Try using a float instead of an int.
Not for integer division. Zero is the correct result, except when "foo" is 1.
An integer is an integral whole number without a decimal point. These numbers are used for counting. For example 26, 373, –1729 are valid integers. Normally an integer can hold numbers from -32768 to 32767. However, if the need is, a long integer (long int) can also be used to hold integers from -2, 147, 483, 648 to 2, 147, 483, 648.
Ok, I guess that one of the two operators must be a float to get a float. But in my real case, a = 20000. In that case, the result is 0 again.
So basically go for
Serial.println(1.0/foo, 6); // print with 6 digits after decimal point
If you don’t provide any count of digits after the decimal point, the default value is 2 so you’ll get 0.00 if your number is smaller than this when rounded
Every time
Let's be clear about this. You are not inverting the number, you are trying to take the reciprocal of the number.
At least in Dutch 1/x is named the inverse number of x.
For 1/x it happens that the inverse function is equal to 1/x (1/x is its own inverse).
If you take x=4, 1/x = 0.25. If you take 1/ 0.25 =4
Like with sin(PI/2) = 1. and using inverse function: sin^-1(1) =PI/2.
Not a coincidence: 1/x may be written as x^-1 (the inverse of x, exactly like sin^-1 is the inverse of sin).
To be fully corect: this does not hold for x=0.
And for sin you will lose the amount of full periods during this operation (your result will always be between -PI and +PI.
In French we call this also the “inverse”
So may be a cultural/translation issue
I’ve read many math works where they mention the additive inverse and the multiplicative inverse (and indeed they call the latter also the reciprocal in English)
The inverse is linked to the operation being used to give you the identity element so 0 for addition/soustraction and 1 for multiplication/division. For a general function f(x) you will have f-1(x) so that when you combine them you get the identity function. Some operations (like sampling analog values or f(x) = x2) don’t have one inverse function (you lost information and can’t go back)
This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.