grails how to check Double negative zero - grails

I googled the answer. They said use Double.compare().
It does not work.
Double.compare(-0d, 0d) < 0
This gives me false. Should be true.
Math.signum() does not work with -0d. The document says it will give me back -0d.
On the other hand, if I have a formula that calculate the value to be -zero, compare gives me a different answer.
def xyz = -0d
Double.compare(xyz, 0d) < 0 will give me false
def xyz = 0d * -1d
Double.compare(xyz, 0d) < 0 will give me true
Is this a bug in Grails?

Why do you expect comparing -0d with 0d to be not equal?
Double.compare(-0d, 0d) < 0// returns false
cause
Double.compare(-0d, 0d) == 0 //returns true

Related

Using loop to solve if number < than 200 previous numbers, return 1

I'm writing a small program in lua and I was hoping to get some pointers on what would be the most correct way to approach this. Basically, if my number is bigger than the last 200 numbers, return 1, else return 0.
I figure the best way would be a loop?
Let's say x is the position of my number in a table, and then I want to check that it's bigger than the previous 200 numbers and return 1 at the end if it is and 0 if it's not.
while (x > x-a)
do
isbigger = 1;
a = a+1;
return isbigger;
end
I'm not sure if that's correct syntax wise, it also would technically return 1 everytime it goes through the loop and I just want it at the end if true that my number is bigger than the 200 previous one. Also, how do get out of the loop if its false (I'd guess with a break)?
Thanks for any help and have a nice day!
If you are looping over an array of values, you should use a for loop. you also do not want to return isbigger from inside the loop as it will prematurely end the loop
local last = 10
local myNumber = 123
local numbers = {}
--Setup our example numbers table
math.randomseed(os.clock())
for i = 1, 40 do
numbers[i] = math.random(1,200)
end
--Run comparison on our the last x values
local isBigger = true
for i = #numbers, #numbers - last, -1 do
print(myNumber, numbers[i], myNumber > numbers[i])
isBigger= isBigger and myNumber > numbers[i]
end
print("isBigger is: " .. isBigger)
return isBigger and 1 or 0
Example Output
123 181 false
123 6 true
123 77 true
123 78 true
123 145 false
123 130 false
123 104 true
123 114 true
123 6 true
123 4 true
123 15 true
isBigger is: false
The for loop above is better for understanding what is happening, but this one is better for use as it will exit once it has found an result that shows myNumber is not bigger.
local isBigger = true
for i = #numbers, #numbers - last, -1 do
print(myNumber, numbers[i], myNumber > numbers[i])
if not (myNumber > numbers[i]) then
isBigger = false
break
end
end

Is there a way to perform if-else using collect in ruby and update an array

$days = 25
action_count = [0,0,0]
if $days < 0
action_count[0] += 1
elsif $days <= 20
action_count[1] += 1
else
action_count[2] += 1
end
Can this if-else code be shortened using collect in ruby
I can't think of a way to do this using collect, but you could use Enumerable#bsearch_index.
If $days is an integer, this does the same thing as your if; but it is not very readable. (Integer, because there is a slight problem that you are using two different comparisons, and I'm assuming $days <= 20 is the same as $days < 21).
action_count[[0, 21].bsearch_index { |x| $days < x } || -1] += 1
bsearch_index finds whether $days is lower than 0, 21 or neither, returning 0, 1 or nil. We replace the nil case with -1 (last element), and we have an index we can use to increment an appropriate element of action_count.

Printing 0 to 50 inclusive?

Why is this code not printing 0 to 50 inclusive?
i = 0
until i <= 50 do
print i
i += 1
end
Either use
until i > 50 do
# ...
end
or
while i <= 50 do
# ...
end
Here's a more "Ruby like" example:
(0..50).each do |i|
puts i
end
Ugh.
i = 0
until i <= 50 do
print i
i += 1
end
That would generate 51 iterations because you're starting at 0 and trying to run until 50 is reached, except that until is "notting" your condition. If you want to loop perhaps while would be a better test:
i = 0
while i <= 50 do
print i
i += 1
end
>> 01234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950nil
But, even with while there are still 51 values being output:
i = 0
output = []
while i <= 50 do
output << i
i += 1
end
output.size # => 51
If you want to loop 50 times, why not use:
50.times do |i|
puts i
end
Or:
50.times { |i| puts i }
Change until to while. until is basically the same thing as while, but the conditional is inverted.
Another iterative method to use would be upto:
0.upto(50) do |i|
puts i
end
I really love this method for quick number iterations. It's super idiomatic (it does what it says) and it's inclusive of both start and end values so you don't have to calculate/account for an exclusive end val.
until stops executing when the condition it has is true. Because it is true from the beginning, nothing happens.
Just swap the comparison operators.
i = 0
until i > 50 do
print i
i += 1
end
You could also do
i = 0
while i <= 50 do
print i
i += 1
end
Use Idiomatic Ruby
Other answers have addressed why your original code doesn't work, and have pointed out the logic error in your conditional. However, it's worth noting that a more idiomatic way to do what you're doing would avoid the conditional altogether. For example:
(1..50).each { |i| pp i }
This works. ;)
i = 1
while i < 51 do
print i
i += 1
end
the first thing you have the comparison sing backwards
you want to do something like:
i = 0
until i >= 50 do
print i
i += 1
end
you can take a look at http://ruby-doc.org/core-2.1.2/doc/syntax/control_expressions_rdoc.html#label-until+Loop for more info

Lua Prime Number Checker

Here is my Lua code for taking user input, and checking if the number entered is prime. My issue is that the program thinks that any even number is not prime, and any odd number is.
print("Enter a number.")
local number = io.read("*n")
function prime(n)
for i = 2, n^(1/2) do
if (n % i) == 0 then
return false
end
return true
end
end
if prime(number) == true then
print("Your number is prime!")
end
if prime(number) == false then
print("Your number is not prime!")
end
Move return true out of the loop.
Hence:
function prime(n)
for i = 2, n^(1/2) do
if (n % i) == 0 then
return false
end
end
return true
end
You return true too soon. You return true as soon as any i meets the condition. You must place the return after the loop.
I know it's an old post but since it's near the top on google I figured it can't hurt to post up my prime finder. It basically does a few simple checks of the obvious stuff and then loops through whats left in a similar fashion to the first example in Jon Ericson' post. Haven't benchmarked it but it seems to cope well enough.
--returns true if prime
function isPrime(n)
local n = tonumber(n)
--catch nil, 0, 1, negative and non int numbers
if not n or n<2 or (n % 1 ~=0) then
return false
--catch even number above 2
elseif n>2 and (n % 2 == 0) then
return false
--primes over 5 end in 1,3,7 or 9
--catch numbers that end in 5 or 0 (multiples of 5)
elseif n>5 and (n % 5 ==0) then
return false
--now check for prime
else
--only do the odds
for i = 3, math.sqrt(n), 2 do
--did it divide evenly
if (n % i == 0) then
return false
end
end
--can defeat optimus
return true
end
end
If you are going to be checking primality, you might as well pick an efficient algorithm. As one answer (cryptically) pointed out, all even numbers greater than 2 are not prime. Therefore, you can short-circuit the check for half the numbers, which doubles the speed to check any particular number:
function check_prime (x)
-- Negative numbers, 0 and 1 are not prime.
if x < 2 then
return false
end
-- Primality for even numbers is easy.
if x == 2 then
return 2
end
if x%2 == 0 then
return false
end
-- Since we have already considered the even numbers,
-- see if the odd numbers are factors.
for i = 3, math.sqrt(x), 2 do
if x%i == 0 then
return false
end
end
return x
end
There are all sorts of optimizations we could apply, but let's take a shot at doing this in a more Lua manner:
function sieve (x)
if x < 2 then
return false
end
-- Assume all numbers are prime until proven not-prime.
local prime = {}
prime[1] = false
for i = 2, x do
prime[i] = true
end
-- For each prime we find, mark all multiples as not-prime.
for i = 2, math.sqrt(x) do
if prime[i] then
for j = i*i, x, i do
prime[j] = false
end
end
end
return prime
end
To use the sieve function:
prime = sieve(number)
if prime[number] then
print("Your number is prime!")
else
print("Your number is not prime!")
end
In my tests, the sieve version is about 6 times faster than the previous algorithm for generating all the primes less than 1 million. (Your mileage may vary.) You can easily check the primality of all numbers less than number at no extra cost. On the other hand, it uses more memory and if you really want check the primality of just one number, it's less efficient.
I would check for primes by dividing the number with 2 and checking if the floor of the division is equal to the division. It looks like this.
if (input/2 == math.floor(input/2)) then
print("is prime")
else
print("is not prime")
end

Lua: Random: Percentage

I'm creating a game and currently have to deal with some math.randomness.
As I'm not that strong in Lua, how do you think
Can you make an algorithm that uses math.random with a given percentage?
I mean a function like this:
function randomChance( chance )
-- Magic happens here
-- Return either 0 or 1 based on the results of math.random
end
randomChance( 50 ) -- Like a 50-50 chance of "winning", should result in something like math.random( 1, 2 ) == 1 (?)
randomChance(20) -- 20% chance to result in a 1
randomChance(0) -- Result always is 0
However I have no clue how to go on, and I completely suck at algorithms
I hope you understood my bad explanation of what I'm trying to accomplish
With no arguments, the math.random function returns a number in the range [0,1).
Lua 5.1.4 Copyright (C) 1994-2008 Lua.org, PUC-Rio
> =math.random()
0.13153778814317
> =math.random()
0.75560532219503
So simply convert your "chance" to a number between 0 and 1: i.e.,
> function maybe(x) if math.random() < x then print("yes") else print("no") end end
> maybe(0.5)
yes
> maybe(0.5)
no
Or multiply the result of random by 100, to compare against an int in the range 0-100:
> function maybe(x) if 100 * math.random() < x then print(1) else print(0) end end
> maybe(50)
0
> maybe(10)
0
> maybe(99)
1
Yet another alternative is to pass the upper and lower limits to math.random:
> function maybe(x) if math.random(0,100) < x then print(1) else print(0) end end
> maybe(0)
0
> maybe(100)
1
I wouldn't mess around with floating-point numbers here; I'd use math.random with an integer argument and integer results. If you pick 100 numbers in the range 1 to 100 you should get the percentages you want:
function randomChange (percent) -- returns true a given percentage of calls
assert(percent >= 0 and percent <= 100) -- sanity check
return percent >= math.random(1, 100) -- 1 succeeds 1%, 50 succeeds 50%,
-- 100 always succeeds, 0 always fails
end

Resources