Rounding some numbers, and converting some to int - ruby

I made a method that takes two numbers and returns a calculated value rounded to three decimals. I'm curious to know how I can have numbers such as 1.141 to be rounded but numbers like 5.0 turned into integers (5).
code:
def calculateHypotenuse(a,b)
if (a <= 0 || b <= 0)
return raise
end
c = Math.sqrt((a * a) + (b * b))
return c.round(3)
end

not sure there is a built in function for floats, but a hackish way could be something like this.
def conditional_truncation(x)
x.truncate == x ? x.truncate : x
end
conditional_truncation(1.141)
=> 1.141
conditional_truncation(5.0)
=> 5

Related

Ruby : unexpected ',', expecting '.' or &. or :: or '['

I'm currently trying to implement a mathematic method to approximate
f(x) = 0. I've already implemented it in some languages and I want to do it in ruby now just for training.
But I have this error that I really does'nt understand
Here is my code
def fonction (x)
return (x ** 3) + 4 * (x ** 2) - 10
end
def derive (x)
return 3 * (x ** 2) + 8 * x
end
def newton(f, fPrime, n, u0)
if n == 0 then
return u0
else
uN = newton (f, fPrime, (n - 1), u0)
return uN - f(uN) / fPrime(uN)
end
end
for i in 0..6
puts (newton (fonction, derive, i, 2))
end
i think there is space on newton method call
uN = newton (f, fPrime, (n - 1), u0) # there is space after newton
also in this one
for i in 0..6
puts (newton (fonction, derive, i, 2)) # there is space after newton
end
try remove it, and you will see another error i guess, i try it on repl

Is there a way to cast a a set of unequal line segments to enum without conditional constructions?

So, basically, I have implemented a naive rarity system, where I have randomly generated byte values(0-255). From them I determine an enum variable as such:
case < 100:
return 0;
case > 100 and < 180:
return 1;
case >180 and <235:
return 2;
case > 235:
return 3;
So now I'm at the point, where I would like to improve some of my code and this method keeps bothering me. As you can see, values, corresponding to different enum numbers, are unequal. And I started wondering, is there a way to represent this kind of a cast with a formula? I fidgeted a bit with it, but I'm really no mathematician) So I'd appreciate some help
If you want those exact rarity thresholds, then I would write something like rarity1.
If you're a little flexible, you could do rarity2 or rarity3. For rarity2, in essence, we interpret b as a fixed point fraction x ∈ [0, 1) and return ⌊4x²⌋. The boundaries are x = 1/2, x = 1/√2, x = √3/2, i.e., b = 128, b = 182, b = 222.
The rarity3 alternative is not monotone. It takes the min of the upper and lower 2-bit quantities. The outcome probabilities are 7/16, 5/16, 3/16, 1/16, corresponding to decision boundaries 112, 192, 240.
def rarity1(b):
if b < 100:
return 0
elif b < 180:
return 1
elif b < 235:
return 2
else:
return 3
def rarity2(b):
return (b * b) >> 14
def rarity3(b):
return min(b >> 6, b & 3)

Recursion for raising a number to a power

I have this code:
def power(x, n)
if n == 1
return x
else
x = x * power(x, n-1)
end
end
power(4, 4)
power(2, 3)
power(10, 3)
power(25, 2)
power(6, 5)
It takes the first number and raises it to the 2nd numberth power. So it works for all of them, but I want to write the code in a way that it prints the results for all 5 of the power functions. How do I do this? I tried to modify with puts instead of return but I cannot get it to work.
You have a variable x which points to the result of the method call. You can print this and then return it from the function:
def power(x, n)
if n == 1
return x
else
x = x * power(x, n-1)
puts x
x
end
end

Exponentiation program

I am trying to do a fast exponentiation. But the result does not seem to produce the correct result. Any help would be appreciated.
EDIT: Manage to solve it thanks for all the help.
if (content[i] == '1')
s1 = (int)(po1 * (Math.pow(po1, 2)));
else
s1 = po1 * po1;
final_result *= temp;
Check out this Exponation by squaring
You probably want to bit-shift right and square your base each time you encounter a 1 bit in the exponent
int pow(int base, int e)
{
int retVal = 1;
while (e)
{
if (e % 2 == 1)//i.e. last bit of exponent is 1
retVal *= base;
e >>= 1; //bitshift exponent to the right.
base *= base; // square base since we shifted 1 bit in our exponent
}
return retVal ;
}
A good way of thinking about it is that your exponent is being broken down: say, 6^7 (exponent in bits is 1, 1, 1) = 6^1 * 6^2 * 6^4 = 6 * 36 * 36^2 = 6 * 36 * 1296. Your base is always squaring itself.
temp = (int)(g1 * (Math.pow(g1, 2)));
This basically just boils down to g13. I'm not familiar with this algorithm but this can't be right.
Also, as a side note, don't ever call Math.pow(<var>, 2), just write <var> * <var>.
There are several problems with your code, starting with the fact that you are reading the exp string in the wrong direction, adding extra multiplications by the base, and not considering the rank of the 1 when raising the powers of 2.
Here is a python quick sketch of what you are trying to achieve:
a = int(raw_input("base"))
b = "{0:b}".format(int(raw_input("exp")))
res = 1
for index, i in enumerate(b[::-1]):
if i == '1':
res *= a**(2**index)
print res
Alternatively, you could square a at every iteration instead:
for index, i in enumerate(b[::-1]):
if i == '1':
res *= a
a *= a

I have a numeric value like 30.6355 that represents money, how to round to 2 decimal places?

I have a numeric value like 30.6355 that represents money, how to round to 2 decimal places?
You should not use double or float types when dealing with currency: they have both too many decimal places and occasional rounding errors. Money can fall through those holes and it'll be tough to track down the errors after it happens.
When dealing with money, use a fixed decimal type. In Ruby (and Java), use BigDecimal.
Ruby 1.8:
class Numeric
def round_to( places )
power = 10.0**places
(self * power).round / power
end
end
(30.6355).round_to(2)
Ruby 1.9:
(30.6355).round(2)
In 1.9, round can round to a specified number of digits.
This will round for some useful cases - not well written but it works! Feel free to edit.
def round(numberString)
numberString = numberString.to_s
decimalLocation = numberString.index(".")
numbersAfterDecimal = numberString.slice(decimalLocation+1,numberString.length-1)
numbersBeforeAndIncludingDeciaml = numberString.slice(0,decimalLocation+1)
if numbersAfterDecimal.length <= 2
return numberString.to_f
end
thingArray = numberString.split("")
thingArray.pop
prior = numbersAfterDecimal[-1].to_i
idx = numbersAfterDecimal.length-2
thingArray.reverse_each do |numStr|
if prior >= 5
numbersAfterDecimal[idx] = (numStr.to_i + 1).to_s unless (idx == 1 && numStr.to_i == 9)
prior = (numStr.to_i + 1)
else
prior = numStr.to_i
end
break if (idx == 1)
idx -= 1
end
resp = numbersBeforeAndIncludingDeciaml + numbersAfterDecimal[0..1]
resp.to_f
end
round(18.00) == 18.0
round(18.99) == 18.99
round(17.9555555555) == 17.96
round(17.944444444445) == 17.95
round(15.545) == 15.55
round(15.55) == 15.55
round(15.555) == 15.56
round(1.18) == 1.18
round(1.189) == 1.19

Resources