the operation % in Dart return a strange value% work in Dart - dart

The var c return 3 but 10/7=1.4285, the rest is 0.4285, operator % has a bug?
void main() {
var a = 10;
var b = 7;
var c;
c = a % b;
print(c);
}

From the documentation of the % operator on num in Dart:
Euclidean modulo operator.
Returns the remainder of the Euclidean division. The Euclidean division of two integers a and b yields two integers q and r such that a == b * q + r and 0 <= r < b.abs().
The Euclidean division is only defined for integers, but can be easily extended to work with doubles. In that case r may have a non-integer value, but it still verifies 0 <= r < |b|.
The sign of the returned value r is always positive.
See remainder for the remainder of the truncating division.
https://api.dart.dev/stable/2.8.4/dart-core/num/operator_modulo.html

The '%' operator returns the remainder left after dividing two numbers. It does not return the decimal part. For example:
10 / 7
1
______
7 ) 10
- 7
______
3
So it returns 3 which is what remains after dividing 10 by 7 without any decimals.
10 / 7 = 1 3/7
What you want to do can be accomplished like this:
var floatNumber = 12.5523;
var x = floatNumber - floatNumber.truncate();

Related

How to get each individual digit of a given number in Basic?

I have one program downloaded from internet and need to get each digit printed out from a three digit number. For example:
Input: 123
Expected Output:
1
2
3
I have 598
Need to Get:
5
9
8
I try using this formula but the problem is when number is with decimal function failed:
FIRST_DIGIT = (number mod 1000) / 100
SECOND_DIGIT = (number mod 100) / 10
THIRD_DIGIT = (number mod 10)
Where number is the above example so here is calulation:
FIRST_DIGIT = (598 mod 1000) / 100 = 5,98 <== FAILED...i need to get 5 but my program shows 0 because i have decimal point
SECOND_DIGIT = (598 mod 100) / 10 = 9,8 <== FAILED...i need to get 9 but my program shows 0 because i have decimal point
THIRD_DIGIT = (598 mod 10) = 8 <== CORRECT...i get from program output number 8 and this digit is correct.
So my question is is there sample or more efficient code that get each digit from number without decimal point? I don't want to use round to round nearest number because sometime it fill failed if number is larger that .5.
Thanks
The simplest solution is to use integer division (\) instead of floating point division (/).
If you replace each one of your examples with the backslash (\) instead of forward slash (/) they will return integer values.
FIRST_DIGIT = (598 mod 1000) \ 100 = 5
SECOND_DIGIT = (598 mod 100) \ 10 = 9
THIRD_DIGIT = (598 mod 10) = 8
You don't have to do any fancy integer calculations as long as you pull it apart from a string:
INPUT X
X$ = STR$(X)
FOR Z = 1 TO LEN(X$)
PRINT MID$(X$, Z, 1)
NEXT
Then, for example, you could act upon each string element:
INPUT X
X$ = STR$(X)
FOR Z = 1 TO LEN(X$)
Q = VAL(MID$(X$, Z, 1))
N = N + 1
PRINT "Digit"; N; " equals"; Q
NEXT
Additionally, you could tear apart the string character by character:
INPUT X
X$ = STR$(X)
FOR Z = 1 TO LEN(X$)
SELECT CASE MID$(X$, Z, 1)
CASE " ", ".", "+", "-", "E", "D"
' special char
CASE ELSE
Q = VAL(MID$(X$, Z, 1))
N = N + 1
PRINT "Digit"; N; " equals"; Q
END SELECT
NEXT
I'm no expert in Basic but looks like you have to convert floating point number to Integer. A quick google search told me that you have to use Int(floating_point_number) to convert float to integer.
So
Int((number mod 100)/ 10)
should probably the one you are looking for.
And, finally, all string elements could be parsed:
INPUT X
X$ = STR$(X)
PRINT X$
FOR Z = 1 TO LEN(X$)
SELECT CASE MID$(X$, Z, 1)
CASE " "
' nul
CASE "E", "D"
Exponent = -1
CASE "."
Decimal = -1
CASE "+"
UnaryPlus = -1
CASE "-"
UnaryNegative = -1
CASE ELSE
Q = VAL(MID$(X$, Z, 1))
N = N + 1
PRINT "Digit"; N; " equals"; Q
END SELECT
NEXT
IF Exponent THEN PRINT "There was an exponent."
IF Decimal THEN PRINT "There was a decimal."
IF UnaryPlus THEN PRINT "There was a plus sign."
IF UnaryNegative THEN PRINT "There was a negative sign."

Get result from modulo operation in ios swift [duplicate]

How does modulo of negative numbers work in swift ?
When i did (-1 % 3) it is giving -1 but the remainder is 2. What is the catch in it?
The Swift remainder operator % computes the remainder of
the integer division:
a % b = a - (a/b) * b
where / is the truncating integer division. In your case
(-1) % 3 = (-1) - ((-1)/3) * 3 = (-1) - 0 * 3 = -1
So the remainder has always the same sign as the dividend (unless
the remainder is zero).
This is the same definition as required e.g. in the C99 standard,
see for example
Does either ANSI C or ISO C specify what -5 % 10 should be?. See also
Wikipedia: Modulo operation for an overview
how this is handled in different programming languages.
A "true" modulus function could be defined in Swift like this:
func mod(_ a: Int, _ n: Int) -> Int {
precondition(n > 0, "modulus must be positive")
let r = a % n
return r >= 0 ? r : r + n
}
print(mod(-1, 3)) // 2
From the Language Guide - Basic Operators:
Remainder Operator
The remainder operator (a % b) works out how many multiples of b
will fit inside a and returns the value that is left over (known as
the remainder).
The remainder operator (%) is also known as a modulo operator in
other languages. However, its behavior in Swift for negative numbers
means that it is, strictly speaking, a remainder rather than a modulo
operation.
...
The same method is applied when calculating the remainder for a
negative value of a:
-9 % 4 // equals -1
Inserting -9 and 4 into the equation yields:
-9 = (4 x -2) + -1
giving a remainder value of -1.
In your case, no 3 will fit in 1, and the remainder is 1 (same with -1 -> remainder is -1).
If what you are really after is capturing a number between 0 and b, try using this:
infix operator %%
extension Int {
static func %% (_ left: Int, _ right: Int) -> Int {
if left >= 0 { return left % right }
if left >= -right { return (left+right) }
return ((left % right)+right)%right
}
}
print(-1 %% 3) //prints 2
This will work for all value of a, unlike the the previous answer while will only work if a > -b.
I prefer the %% operator over just overloading %, as it will be very clear that you are not doing a true mod function.
The reason for the if statements, instead of just using the final return line, is for speed, as a mod function requires a division, and divisions are more costly that a conditional.
An answer inspired by cdeerinck, which sacrifices speed for simplicity, is this:
infix operator %%
extension Int {
static func %% (_ left: Int, _ right: Int) -> Int {
let mod = left % right
return mod >= 0 ? mod : mod + right
}
}
I tested it with this little loop in a playground:
for test in [6, 5, 4, 0, -1, -2, -100, -101] {
print(test, "%% 5", test %% 5)
}

"%" and "/" simbols difference in Ruby

I'm trying to solve the FizzBuzz game.
I need to check if a number is divisible by 3. So, when we take a number and divide it by 3, we need that operation to have NO REST, or 0 REST.
The solution given to me is this:
def fizzbuzz(number)
if number % 3 == 0
return "Fizz"
end
Why does they propose to use the "%"symbol? Why not the "/"symbol? Or both work as the same?
How should I check if the division has NO REST?
division operator / - gives the quotient of the division whatever the remainder of the division is. So you cannot determine if a number is perfectly divisible (remainder = 0) or not perfectly divisible (with non-zero remainder) using a division operator (/).
10 / 3
#=> 3
modulo operator % - gives the remainder of the division. If perfectly divisible, the output is 0, if not-perfectly divisible the output is non-zero value.
10 % 3
#=> 1
In your case number % 3 == 0 is true only if number is divisible by 3 with 0 remainder (i.e if number passed into the method frizzbuzz is a multiple of 3 like -12, -3, 3, 6, 9, etc )
Ruby has 4 division operators.
divmod returns the division and the remainder
number = 15
number.divmod(7) # => 2, 1
modulo alias % returns the remainder only
number = 15
number % 7 # => 1
number.modulo(7) # => 1
div alias / returns the integer division if both operands are integers, and floating-point division if either operand is a float.
number = 15
number / 7 # => 2
number.div(7) # => 2
1.0 * number / 7 # => 2.142857142857143
fdiv always returns a full precision floating-point division
number = 15
number.fdiv(7) # => 2.142857142857143
% is the Modulus - Divides left hand operand by right hand operand and returns remainder. \ is just the Divider. No Rest means that x % y == 0.
lets take an example to understand better:
number1 = 12
number2 = 13
lets see if number1 and number2 is devisible by 4 ok?
number1 / 4 = 3 and the rest = 0
number2 / 4 = 3 and the rest = 1
so the "/" operation let us know the result of devision operation
and the "%" operation let us know the rest of devision operation
so if we take our examples the number1 is devisible by 3 because
number1 % 3 = 0 ( the rest )

List comprehensions with float iterator in F#

Consider the following code:
let dl = 9.5 / 11.
let min = 21.5 + dl
let max = 40.5 - dl
let a = [ for z in min .. dl .. max -> z ] // should have 21 elements
let b = a.Length
"a" should have 21 elements but has got only 20 elements. The "max - dl" value is missing. I understand that float numbers are not precise, but I hoped that F# could work with that. If not then why F# supports List comprehensions with float iterator? To me, it is a source of bugs.
Online trial: http://tryfs.net/snippets/snippet-3H
Converting to decimals and looking at the numbers, it seems the 21st item would 'overshoot' max:
let dl = 9.5m / 11.m
let min = 21.5m + dl
let max = 40.5m - dl
let a = [ for z in min .. dl .. max -> z ] // should have 21 elements
let b = a.Length
let lastelement = List.nth a 19
let onemore = lastelement + dl
let overshoot = onemore - max
That is probably due to lack of precision in let dl = 9.5m / 11.m?
To get rid of this compounding error, you'll have to use another number system, i.e. Rational. F# Powerpack comes with a BigRational class that can be used like so:
let dl = 95N / 110N
let min = 215N / 10N + dl
let max = 405N / 10N - dl
let a = [ for z in min .. dl .. max -> z ] // Has 21 elements
let b = a.Length
Properly handling float precision issues can be tricky. You should not rely on float equality (that's what list comprehension implicitely does for the last element). List comprehensions on float are useful when you generate an infinite stream. In other cases, you should pay attention to the last comparison.
If you want a fixed number of elements, and include both lower and upper endpoints, I suggest you write this kind of function:
let range from to_ count =
assert (count > 1)
let count = count - 1
[ for i = 0 to count do yield from + float i * (to_ - from) / float count]
range 21.5 40.5 21
When I know the last element should be included, I sometimes do:
let a = [ for z in min .. dl .. max + dl*0.5 -> z ]
I suspect the problem is with the precision of floating point values. F# adds dl to the current value each time and checks if current <= max. Because of precision problems, it might jump over max and then check if max+ε <= max (which will yield false). And so the result will have only 20 items, and not 21.
After running your code, if you do:
> compare a.[19] max;;
val it : int = -1
It means max is greater than a.[19]
If we do calculations the same way the range operator does but grouping in two different ways and then compare them:
> compare (21.5+dl+dl+dl+dl+dl+dl+dl+dl) ((21.5+dl)+(dl+dl+dl+dl+dl+dl+dl));;
val it : int = 0
> compare (21.5+dl+dl+dl+dl+dl+dl+dl+dl+dl) ((21.5+dl)+(dl+dl+dl+dl+dl+dl+dl+dl));;
val it : int = -1
In this sample you can see how adding 7 times the same value in different order results in exactly the same value but if we try it 8 times the result changes depending on the grouping.
You're doing it 20 times.
So if you use the range operator with floats you should be aware of the precision problem.
But the same applies to any other calculation with floats.

Scaling a number between two values

If I am given a floating point number but do not know beforehand what range the number will be in, is it possible to scale that number in some meaningful way to be in another range? I am thinking of checking to see if the number is in the range 0<=x<=1 and if not scale it to that range and then scale it to my final range. This previous post provides some good information, but it assumes the range of the original number is known beforehand.
You can't scale a number in a range if you don't know the range.
Maybe what you're looking for is the modulo operator. Modulo is basically the remainder of division, the operator in most languages is is %.
0 % 5 == 0
1 % 5 == 1
2 % 5 == 2
3 % 5 == 3
4 % 5 == 4
5 % 5 == 0
6 % 5 == 1
7 % 5 == 2
...
Sure it is not possible. You can define range and ignore all extrinsic values. Or, you can collect statistics to find range in run time (i.e. via histogram analysis).
Is it really about image processing? There are lots of related problems in image segmentation field.
You want to scale a single random floating point number to be between 0 and 1, but you don't know the range of the number?
What should 99.001 be scaled to? If the range of the random number was [99, 100], then our scaled-number should be pretty close to 0. If the range of the random number was [0, 100], then our scaled-number should be pretty close to 1.
In the real world, you always have some sort of information about the range (either the range itself, or how wide it is). Without further info, the answer is "No, it can't be done."
I think the best you can do is something like this:
int scale(x) {
if (x < -1) return 1 / x - 2;
if (x > 1) return 2 - 1 / x;
return x;
}
This function is monotonic, and has a range of -2 to 2, but it's not strictly a scaling.
I am assuming that you have the result of some 2-dimensional measurements and want to display them in color or grayscale. For that, I would first want to find the maximum and minimum and then scale between these two values.
static double[][] scale(double[][] in, double outMin, double outMax) {
double inMin = Double.POSITIVE_INFINITY;
double inMax = Double.NEGATIVE_INFINITY;
for (double[] inRow : in) {
for (double d : inRow) {
if (d < inMin)
inMin = d;
if (d > inMax)
inMax = d;
}
}
double inRange = inMax - inMin;
double outRange = outMax - outMin;
double[][] out = new double[in.length][in[0].length];
for (double[] inRow : in) {
double[] outRow = new double[inRow.length];
for (int j = 0; j < inRow.length; j++) {
double normalized = (inRow[j] - inMin) / inRange; // 0 .. 1
outRow[j] = outMin + normalized * outRange;
}
}
return out;
}
This code is untested and just shows the general idea. It further assumes that all your input data is in a "reasonable" range, away from infinity and NaN.

Resources