Ceiling to Nearest 50
I can round the elements of A
to the nearest integers greater than or equal to A
ceil(A)
But what about if I want to round it to the nearest 50 greater than or equal to A
?
For example, given the following 开发者_开发百科A
array,
A=[24, 35, 78, 101, 199];
A subroutine should return the following
B=Subroutine(A)=[50, 50, 100, 150, 200];
You could just divide by 50, take ceil(), and multiply by 50 again:
octave:1> A=[24, 35, 78, 101, 199];
octave:2> ceil(A)
ans =
24 35 78 101 199
octave:3> 50*(ceil(A/50.))
ans =
50 50 100 150 200
An easy way is to just add each number's complement modulo 50:
octave> A = [24, 35, 78, 101, 199]
octave> mod(-A, 50) # Complement (mod 50)
ans =
26 15 22 49 1
octave> A + mod(-A, 50) # Sum to "next higher" zero (mod 50)
ans =
50 50 100 150 200
octave> A - mod(A, 50) # Can also sum to "next lower" zero (mod 50)
ans =
0 0 50 100 150
(Note that this only depends on integer arithmetic, which avoids errors due to floating-point rounding.)
精彩评论