How to have a custom rounding function? - vbscript

Basically, I need FormatNumber to behave slightly differently. Of course, we can write our own MyFormatNumber, but basically, it should return the following:
59.080 returns 59.08
59.081 returns 59.08
59.082 returns 59.08
59.083 returns 59.08
59.084 returns 59.09 ←
59.085 returns 59.09
59.086 returns 59.09
59.087 returns 59.09
59.088 returns 59.09
59.089 returns 59.09
As you can see, the only difference is when the 3rd decimal place is a 4, then I would like to round up. That is, when the input's third decimal place is 4 or greater, then do a round up, otherwise round down.
How can we do such a function in Classic ASP?

A custom rounding function could be implemented like this:
Function CustomRound(n)
If n * 1000 Mod 10 < 4 Then
CustomRound = Int(n * 100) / 100
Else
CustomRound = (Int(n * 100) + 1) / 100
End If
End Function

Related

Add percentage to number in Ruby

How can I add a percentage to a number in Ruby?
In this example I want to add 20% to 32.92:
irb(main):001:0> 32.92 * (1 + (20 / 100))
=> 32.92
Google answers with the correct answer; 39.50.
Lets say your base_value is: 39.92.
Your markup is 20.
Integer division will lead to the following:
20 / 100
# => 0
So irb is the right direction. This gives better results:
20.to_f / 100
# => 0.2
So the final calculation will look like this:
final_value = (base_value + (markup.to_f / 100) * base_value).round
This gives you the expected value.
As you don’t mind the result to be floored instead of rounded it’s possible to get correct result using integer division:
final_value = base_value + base_value * markup / 100
20 / 100 returns 0, because it's integer division if you pass integers as arguments. Instead, you can pass floats, like this:
32.92 * (1 + (20.0 / 100.0))
or do simply:
32.92 * 1.2

Integer division with rounding

I need to do integer division. I expect the following to return 2 instead of the actual 1:
187 / 100 # => 1
This:
(187.to_f / 100).round # => 2
will work, but does't seem elegant as a solution. Isn't there an integer-only operator that does 187 / 100 = 2?
EDIT
I'll be clearer on my use case since I keep getting down-voted:
I need to calculate taxes on a price. All my prices are in cents. There is nothing below 1 cent in the accountability world so I need to make sure all my prices are integers (those people checking taxes don't like mistakes... really!)
But on the other hand, the tax rate is 19%.
So I wanted to find the best way to write:
def tax_price(price)
price * TAX_RATE / 100
end
that surely returns an integer, without any floating side effect.
I was afraid of going to the floating world because it has very weird side-effects on number representation like:
Ruby strange issue with floating point multiplication
ruby floating point errors
So I found it safer to stay in the integer or the fractional world, hence my question.
You can do it while remaining in the integer world as follows:
def round_div(x,y)
(x + y / 2) / y
end
If you prefer, you could monkey-patch Fixnum with a variant of this:
class Fixnum
def round_div(divisor)
(self + divisor / 2) / divisor
end
end
187.round_div(100) # => 2
No – (a.to_f / b.to_f).round is the canonical way to do it. The behavior of integer / integer is (for example) defined in the C standard as "discarding the remainder" (see http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1124.pdf page 82) and ruby uses the native C function.
This is a less know method, Numeric#fdiv
You use it like this : 187.fdiv(100).round
Not sure, but this might be what you have in mind.
q, r = 187.divmod(100)
q + (100 > r * 2 ? 0 : 1) # => 2
This should work for you :
Use syntax like this.
(number.to_f/another_number).round
Example:
(18.to_f/5).round
As #MattW already answer (+1), you'd have to cast your integers to floats.
The only other way that is less distracting can be to add .0 to your integer:
(187.0 / 100).round
However, usually we don't operate on concrete integers but variables and this method would be no use.
After some thoughts, I could:
have used BigDecimals but it feels like a bazooka to kill a bird
or I can use a custom method that wouldn't use floating division within the process, as #sawa suggests
def rounded_integer_div(numerator, denominator)
q, r = numerator.divmod(denominator)
q + (100 > r * 2 ? 0 : 1)
end
If what you want is to actually only increase the result by 1 if there's any remainder (e.g. for counting paging/batching), you can use the '%' (modula operation) for remainders checking.
# to add 1 if it's not an even division
a = 187
b = 100
result = a / b #=> 1
result += 1 if (a % b).positive?
#=> 2
# or in one line
result = (a / b) + ((a % b).zero? ? 0 : 1)

Why does .to_s break this code?

I'm working on a Codewars Ruby problem, and don't understand the error I'm seeing. Here are the instructions:
Coding decimal numbers with factorials is a way of writing out numbers
in a base system that depends on factorials, rather than powers of
numbers. In this system, the last digit is always 0 and is in base 0!.
The digit before that is either 0 or 1 and is in base 1!. The digit
before that is either 0, 1, or 2 and is in base 2!. More generally,
the nth-to-last digit in always 0, 1, 2, ..., or n and is in base n!.
Example : decimal number 463 is coded as "341010"
because 463 (base 10) = 3×5! + 4×4! + 1×3! + 0×2! + 1×1! + 0×0!
If we are limited to digits 0...9 the biggest number we can code is
10! - 1.
So we extend 0..9 with letters A to Z. With these 36 digits we can
code up to 36! − 1 = 37199332678990121746799944815083519999999910
(base 10)
We code two functions, the first one will code a decimal number and
return a string with the factorial representation :
"dec2FactString(nb)"
the second one will decode a string with a factorial representation
and produce the decimal representation : "factString2Dec(str)".
Given numbers will be positive.
Note
You can hope tests with Big Integers in Clojure, Python, Ruby, Haskel
but not with Java and others where the number "nb" in
"dec2FactString(nb)" is at most a long.
Ref: http://en.wikipedia.org/wiki/Factorial_number_system
def dec2FactString(nb)
if nb <= 0 then
num = 1
else
num = (nb * dec2FactString(nb - 1))
end
return num
end
Note that this method is only the first half of the problem. This code appears to work inasmuch as it returns the correct factorial, as a Fixnum when using this test:
Test.assert_equals(dec2FactString(4), "24")
Since the instructions ask for a string, I'd normally think that just adding ".to_s" to the num variable would take care of that, but instead I'm seeing a consistent "String can't be coerced into Fixnum (TypeError)" error message. I've tried pushing the output to an array and printing from there, but saw the same error.
I read up on Fixnum a little, and I understand the error in terms of adding a Fixnum to a string won't work, but I don't think I'm doing that in this case - I just want to convert the Fixnum output into a string. Am I missing something?
Observe - this code breaks and produces the error below it:
def dec2FactString(nb)
if nb <= 0 then
num = 1
else
num = (nb * dec2FactString(nb - 1))
end
return num.to_s
end
Example from description
`*': String can't be coerced into Fixnum (TypeError)
from `dec2FactString'
from `dec2FactString'
from `dec2FactString'
from `dec2FactString'
from `block in
'
from `block in describe'
from `measure'
from `describe'
from `
'
You're calling this function recursively. If you calculated the factorial of 1 and left to_s in there, it'd be fine since you're not reusing the variable.
However, if you do place to_s in there, what would you expect the result of num = (nb * dec2FactString(nb - 1)) to be? dec2FactString would be returning a str instead of a Fixnum, and you can't/shouldn't be able to do multiplication between a number and a string.
What you could do is split the responsibilities of stringification and calculation by creating two methods - one that delegates to the recursive function, and one that coerces its result into a string.
def dec2FactString(nb)
return fact(nb).to_s
end
def fact(nb)
if nb <= 0 then
1
else
nb * fact(nb - 1)
end
end
Firstly, Factorial is only defined on non-negative numbers and so your first test is incorrect (if nb <= 0). The recursion should stop when the number is 0 and should return 1 at that point.
Because your recursion returns a string and not a number, you cannot multiply the string by a Fixnum in the next round of recursion. Your recursion can be expanded via the substitution method to the following.
dec2FactString(5)
5 * dec2FactString(4)
5 * 4 * dec2FactString(3)
5 * 4 * 3 * dec2FactString(2)
5 * 4 * 3 * 2 * dec2FactString(1)
5 * 4 * 3 * 2 * 1 * dec2FactString(0)
5 * 4 * 3 * 2 * 1 * "1"
... That is the point where the recursion ends in an error since dec2FactString(0) returns "1"
It would be far better to break it into two functions. One that calculates factorial recursively and one that converts the final answer to a string. Also, you don't need to explicitly return a value in Ruby. The last line of a function is the return value.
I won't give you the complete code as you won't learn anything. As a few hints, do some research on tail call optimisation, recursion and return values in Ruby. This will allow you to craft a better implementation of the recursive function.
Happy coding!

Finding median for even length array in ruby

I cannot figure out why I cannot get the even length portion correct.
def median(array)
array.sort!
if array.length % 2 == 0 #if amount of array members is even
(array[(array.length/2) + 1] + array[array.length/2]) / 2.to_f #return average of the 2 middle array members
else #if amount of array members is odd
array[array.length/2.ceil] #return middle number
end
end
My attempt is for example, an array whose length is 6, and whose 3rd and 4th index value are 7 and 9.
array[6/3+1] + array [6/3]
(array[4] + array[3]) /2
9 + 7 / 2
I am receiving this error
Error!
median returns the correct median of an even-length array
expected: 5.5 got: 6.0 (compared using ==)
I have seen a shorter solution, but am most curious if I can make sense of the logic path I am trying to follow, thanks for playing along!
Solution I have seen:
def median(array)
sorted = array.sort
len = sorted.length
return (sorted[(len - 1) / 2] + sorted[len / 2]) / 2.0
end
Arrays are zero-indexed. So if the length was 4, you need to be taking average of indices 1 and 2. Your current attempt would take average of indices 3 and 2 for a length of 4. So you just need to change one small thing (plus into minus):
(array[(array.length/2) - 1] + array[array.length/2]) / 2.to_f
For an even numbered Fixnum n, this is always true: ( n - 1 ) / 2 == ( n / 2 ) - 1, which means you have figured out a similar approach to the one you found. This is not too surprising, there are a limited number of ways to calculate medians efficiently.
Here is my solution to your whole problem. you need use to -1 that's the reason "arr[(arr.length/2)-1]". Also you can use 2.0 instead of 2.to_f.
#Write a method that finds the median of a given array of integers. If the array has an odd number of integers,
# return the middle item from the sorted array. If the array has an even number of integers,
# return the average of the middle two items from the sorted array.
def find_median(arr)
arr.sort!
if arr.length.even?
return (arr[arr.length/2] + arr[(arr.length/2)-1])/2.0
else #else odd
return arr[arr.length/2.0]
end
end
puts find_median([2,3,4,9,7,8])

Return with a recursive function

I'm curious how return works when using a recursive function. For example, in the factorial function below, x will reach 1 before any calculations can actually occur.
int factorial (int x){
if (x==1){
return 1;
}else{
return x * factorial(x - 1);
}
}
Suppose x = 3. Following the logic, it seems it should loop 3 times and return 1:
3 != 1
so else: 3 * factorial (2).
What's factorial (2)?
Well return to top: 2 != 1
so else: 2 * factorial (1).
What's factorial (1)?
Return to top: 1 == 1,
so: return 1.
But, of course it will actually return 6. So how does it work, exactly?
Every time you say "well what's the value from that recursive call?", you're dropping the x * from the previous iteration. Without doing that:
factorial(3)
3 * factorial(2)
3 * (2 * factorial(1))
3 * (2 * 1)
= 6
Recursive calling is not like a goto to the top of the function again with new arguments.1 We call the function again with new arguments, but only that invocation has the new argument value: the caller still has the old value of its arguments and variables.
1 Unless we're talking about tail recursion, which we aren't, and that's just an optimization anyways.
It's not returning to top, it's invoking the factorial function inside the factorial function.
Indeed, at the end, it returns 1, but it returns it as a result in the line
return x * factorial(x - 1);
of the previous call to factorial, where x was 2. This in turn returns 2 * 1 to the previous call to factorial where x was 3. So this gives 3 * 2, returning the result - 6 - to the first invocation of the function.
A recursive function call is no different from an ordinary function call. So there's no connection between the return of one call and the return of another.
In the example, the first return statement is
return 3 * factorial(2)
which multiplies 3 by the return value of calling factorial with an argument of 2.
But the return value of factorial(2) is
return 2 * factorial(1)
which multiplies 2 by the return value of calling factorial with an argument of 1.
But the return value of factorial(1) is 1.
So return 2 * factorial(1) is the same as return 2 * 1, which is 2.
So return 3 * factorial(2) is the same as return 3 * 2, which is 6.
In the first step, x = 3. Your function then returns 3 * factorial(2), which itself returns 2 * factorial(1) (since x still isn't equal to 1), and finally, factorial(1) returns 1.
So in the end you get 3 * 2 * 1 = 6.
Stack frame is a record that is used at run time to store information about a function call, including the parameters, local variables, register values, and return address. For each successive function calls we are pushing stack frame into stack and when any active function (function which is at top of the stack) gets return call, it’s stack frame is popped up from the stack and the function below it gets active. Here is the example.
So, finally the function factorial(3) return value 6.

Resources