Unexpected result from math expression - ruby

i am using ruby irb
-1/4
=> -1
0-1
=> -1
0-1/4
=> 0
How come it'll be zero for 0-1/4 ?
My calculation is as shown in below pic

1/4 is zero - since both operands are integers, the result is floored to an integer as well. This is the same behavior you're observing earlier with -1/4.
If you want a non-integer result, one or both of the operands have to be floats. For example:
0 - 1 / 4.to_f
to_f makes the interpreter interpret the number as a float.
edit: Your calculation is wrong, by the way. 0 - 1/4 is NOT the same as (0-1) / 4. Always do your operations in the correct order!

Because 1 / 4 is 0. And 0 - 0 is 0.
0 - (1 / 4)
You want this:
(0 - 1) / 4
This way you make sure that subtraction happens first. Read up on operator precedence.

Related

Understanding this snippet 'D' * (num % 1000 / 500)

Can anyone explain how to read this code and what it will do?
'D' * (num % 1000 / 500)
It is from a method for converting integers to Roman numerals. I don't understand how it functions.
It is pretty obfuscated indeed. I guess the idea was to put one or zero Ds depending on if you get a number greater than 500 after you get the remainder of division by 1000.
The order of the operations:
num % 1000
num modulo 1000. Will leave the last three digits.
/ 500
Will see if the last three digits are greater than 500.
String#* repeats a string:
'x' * 5 # => "xxxxx"
The reason that is needed is because D is the letter for 500. You will have only one or zero of these as M is the letter for 1000.
The expression (num % 1000 / 500) means "if you have in your last 3 digits a number greater than 500 then evaluate to 1 otherwise evaluate to 0"
"D" * (0 or 1) is determining whether to put "D" on the roman number or not.
What it Does
The expression is a way of building the Roman numeral five-hundreds digit, which is 'D'.
It takes any number, extracts only the three rightmost digits (values 0 through 999), and returns a 'D' only if the value is 500 or greater. Otherwise it returns an empty string ''
How to Read it
In Ruby, the multiply *, divide /, and modulus % symbols have equal precedence and are processed in order from left to right. Parentheses, however, have a higher precedence than these three operators.
To help visualize the processing order, you can add optional parentheses:
'D' * ( ( num % 1000 ) / 500 )
num % 1000:
extracts the three rightmost digits of a number, resulting in values 0 - 999
{0-999} / 500:
determines if value is 500 or greater, or not.
Returns 1 if so, 0 if not.
In Ruby, integer division does not automatically convert to decimals.
'D' * {1 or 0}:
In Ruby, multiplying a string by 1 returns the string, multiplying by 0 returns an empty string
Examples
For a number 35,045:
35045 % 1000 #=> 45
45 / 500 #=> 0
'D' * 0 #=> ""
For a number 468,987:
468987 % 1000 #=> 987
987 / 500 #=> 1
'D' * 1 #=> "D"
For a number 670:
670 % 1000 #=> 670
670 / 500 #=> 1
'D' * 1 #=> "D"
For a number 7:
7 % 1000 #=> 7
7 / 500 #=> 0
'D' * 0 #=> ""
See this page and scroll down to Ruby Operators Precedence.
Multiplication, division, and modular arithmetic are all together, so precedence is left to right IIRC.
First, num % 1000 is evaluated. Then, that is divided by 500. That's then multiplied by 'D'.
The modulus % and division / operators have the same precedence.
So associativity, which is from left to right for these operators, comes into play.
Therefore the expression is equivalent to 'D' * ((num % 1000) / 500): you are multiplying 'D' by the last 3 digits of num divided by 500.

Multiplication by power series summation with negative terms

How can I calculate a floating point multiplicand in Verilog? So far, I usually use shift << 1024 , then floating point number become to integer. Then I do some operations, then >> 1024 to obtain a fraction again.
For example 0.3545 = 2^-2 + 2^-4 + ...
I have question about another way, like this. I don't know where does the minus (-) comes from:
0.46194 = 2^-1 - 2^-5 - 2^-7 + 2^-10.
I have just look this from someone. but as you way, that is represented like this
0.46194 = 2^-2 + 2^-3 + 2^-4 + 2^-6 + 2^-7 + 2^-10 + .... .
I don't understand how does it know the minus is used it?
How do we know when the minus needed to it? Also how can I apply to verilog RTL?
UPDATE : I understand the concept the using minus in operation. But Is there any other way to equation or methodologies what to make reduce expression what multiplying with power of 2?
UPDATE : how can we use this method in verilog? for example, I have leaned 0.46194 = 2^-1 - 2^-5 - 2^-7 + 2^-10. then this code was written like this in verilog. 0.011101101 ='hED = 'd237. So the point of the question is how can we apply it to application in verilog?
UPDATE : Sir Would you please check this one? there are a little difference result.
0.46194 = 0.011101101. I just tried like this
0.011101101
0.100T10T01
= 2^-1 - 2^-4 + 2^-5 - 2^-7 + 2^-9. = 0.462890625
Something different. What do I wrong?
Multiplication of a variable by a constant is often implemented by adding the variable to shifted versions of itself. This is much cheaper to put on an FPGA than a multiplier circuit accepting two variables.
You can get further savings when there's a sequence of 1-bits in the constant, by using subtraction as well. (A subtraction circuit is only equally expensive as addition.)
Consider the number 30 = 11110. It's equal to 16 + 8 + 4 + 2, but it's also equal to 32 - 2.
In general, a sequence of multiplicand 1-bits, or the sum of several successive powers of two, can be formed by adding the first power of two after the most significant bit, and subtracting the least significant bit. Hence, instead of 16x + ... + 2x, use 32x - 2x.
It doesn't matter if the sequence of 1-bits is part of a fraction or an integer. You're just applying the identity 2^a = 1 + ∑2^0 ... 2^(a-1), in other worsd ∑2^0 ... 2^a = 2^(a+1) - 1.
In a 4 bit base 2 number can have these values:
Base 2: Unsigned 4 bit integer,
2^3 2^2 2^1 2^0
8 4 2 1
If we have a 0111 it represents 7. If we were to multiply by this number using a shift add architecture it would take 3 clockcycles (3 shift and adds).
An optimisation to this is called CSD (Canonical Signed Digit. It allows minus one to be present in the 'binary numbers'. We shall represent -1 as one bar, or T as that looks like a one with a bar over the top.
100T represents 8 - 1 which is the same as 0111. It can be observed that long runs of 1's can be replaced with a the 0 that ends the run becoming 1 and the first 1 of the run becoming a -1, (T).
An example of conversion:
00111101111
01000T1000T
But if passed in two section we would get :
00111101111
0011111000T
010000T000T
We have taken a number that would take 8 clock cycles or 8 blocks of logic to compute and turned it into 3.
Related questions to fixed point values in Verilog x precision binary fixed point representation? and verilog-floating-points-multiplication.
To cover the follow up question:
To answer the follow up section about your question on CSD conversion. I will look at them as pure integers to simplify the numbers, this is the same as multiplying the values by 2^9 (9 fractional bits).
256 128 64 32 16 8 4 2 1
0 1 1 1 0 1 1 0 1
128 + 64 +32 + 8 +4 +1 => 237
Now with your CSD conversion:
256 128 64 32 16 8 4 2 1
1 0 0 T 1 0 T 0 1
256 -32 + 16 - 4 + 1 => 237
You can see your conversion was correct. I get 237* 2^-9 as 0.462890625, which matches your answer when converted back to fractional. The 0.46194 that you started with must have been a rounded version, or when quantised to 9 fractional bits gets truncated. This error is known as quantisation error. The most important thing here though is that you got the CSD conversion correct.

Error correcting codes and minimum distances

I was looking at a challenge online (at King's website) and although I understand the general idea behind it I'm slightly lost - maybe the wording is a little off? Here is the problem and I'll state what I don't understand below:
Error correcting codes are used in a wide variety of applications
ranging from satellite communication to music CDs. The idea is to
encode a binary string of length k as a binary string of length n>k,
called a codeword such that even if some bit(s) of the encoding are
corrupted (if you scratch on your CD for instance), the original k-bit
string can still be recovered. There are three important parameters
associated with an error correcting code: the length of codewords (n),
the dimension (k) which is the length of the unencoded strings, and
finally the minimum distance (d) of the code. Distance between two
codewords is measured as hamming distance, i.e., the number of
positions in which the codewords differ: 0010 and 0100 are at distance
2. The minimum distance of the code is the distance between the two different codewords that are closest to each other. Linear codes are a
simple type of error correcting codes with several nice properties.
One of them being that the minmum distance is the smallest distance
any non-zero codeword has to the zero codeword (the codeword
consisting of n zeros always belongs to a linear code of length n).
Another nice property of linear codes of length n and dimension k is
that they can be described by an n×k generator matrix of zeros and
ones. Encoding a k-bit string is done by viewing it as a column vector
and multiplying it by the generator matrix. The example below shows a
generator matrix and how the string 1001 is encoded. graph.png Matrix
multiplication is done as usual except that additon is done modulo 2
(i.e., 0+1=1+0=1 and 0+0=1+1=0). The set of codewords of this code is
then simply all vectors that can be obtained by encoding all k-bit
strings in this way. Write a program to calculate the minimum distance
for several linear error correcting codes of length at most 30 and
dimension at most 15. Each code will be given as a generator matrix.
Input You will be given several generator matrices as input. The first
line contains an integer T indicating the number of test cases. The
first line of each test case gives the parameters n and k where
1≤n≤30, 1≤k≤15 and n > k, as two integers separated by a single space.
The following n lines describe a generator matrix. Each line is a row
of the matrix and has k space separated entries that are 0 or 1.
Output For each generator matrix output a single line with the minimum
distance of the corresponding linear code.
Sample Input 1
2
7 4
1 0 0 0
0 1 0 0
0 0 1 0
0 0 0 1
0 1 1 1
1 0 1 1
1 1 0 1
3 2
1 1
0 0
1 1
Sample Output 1
3
0
Now my assumption is that the question is asking "Write a program that can take in the linear code in matrix form and say what the minimum distance is from an all zero codeword" I just don't understand why there is a 3 output for the first input and a 0 for the second input?
Very confused.
Any ideas?
For first example:
Input binary string: 1000
Resulting code: 1100001
Hamming distance to zero codeword 0000000: 3
For second example:
Input binary string: 11
Resulting code: 000
Hamming distance to zero codeword 000: 0
Your goal is to find valid non-zero codeword (which can be produced from some non-zero k-bit input string) with minimal Hamming distance to zero codeword (in different words - with minimal amount of ones in binary representation) and return that distance.
Hope that helps, the problem description is indeed a little bit hard to understand.
EDIT. I've made typo in first example. Actual input should be 1000 not 0001. Also it's may be not clear what exactly is input string and how the codeword is calculated. Let's look at first sample.
Input binary string: 1000
This binary string in general is not part of generator matrix. It is just one of all possible non-zero 4-bit strings. Let's multiply it by generator matrix:
(1 0 0 0) * (1 0 0 0) = 1
(0 1 0 0) * (1 0 0 0) = 0
(0 0 1 0) * (1 0 0 0) = 0
(0 0 0 1) * (1 0 0 0) = 0
(0 1 1 1) * (1 0 0 0) = 0
(1 0 1 1) * (1 0 0 0) = 1
(1 1 0 1) * (1 0 0 0) = 1
One way to find input that produces "minimal" codeword is to iterate all 2^k-1 non-zero k-bit strings and calculate codeword for each of them. This is feasible solution for k <= 15.
Another example for first test case 0011 (it's possible to have multiple inputs that produce "minimal" output):
(1 0 0 0) * (0 0 1 1) = 0
(0 1 0 0) * (0 0 1 1) = 0
(0 0 1 0) * (0 0 1 1) = 1
(0 0 0 1) * (0 0 1 1) = 1
(0 1 1 1) * (0 0 1 1) = 2 = 0 (mod 2)
(1 0 1 1) * (0 0 1 1) = 2 = 0 (mod 2)
(1 1 0 1) * (0 0 1 1) = 1
Resulting code 0011001 also has Hamming distance 3 to the zero codeword. There is no 4-bit string with code that has less that 3 ones in binary representation. That's why the answer for first test case is 3.

Fast matrix Exponentiation computation in Galois field

I am looking for a fast way to compute power of matrix A in galois field 2 (GF(2)). A is a double matrix and its exponentiation of x denoted by
A^x = A * A * A * ... * A (x times)
The simple way is that converts A to GF(2) (because given matrix A is double matrix) and then peform exponentiation operation.
Matlab code
A1 = gf(A, 2) % // convert to galois field
A_pow_x_first = A1^x; % // Perform A^x
However, this way takes long time to converts matrix A to GF(2). I am looking for a fast way without GF(2) converting. That is, I using mod operation
A_pow_x_second = mod(A^x, 2)
However, the problem is that the result of first way and second way are not similar. The problem is that overflow of number. Some member suggested to me convert matrix A to int64. However, I think it is not good way to handle with my problem. Could you suggest to me a fast way to do it in matlab? Thanks in advance
This is simple example
>> A = [1 0 1
0 1 1
1 1 1]
First way,
>> A_pow_x_first = gf(A, 2)^50
Result:
0 1 0
1 0 0
0 0 1
Second way
>> A_pow_x_second = mod(A^50, 2)
A_pow_x_second =
0 0 0
0 0 0
0 0 0
How to fast compute A^x without convert to GF(2) that has similar result in first way?

Why is `27 ** (1.0/3.0)` different from `27 ** (1/3)`?

Please let me know if this is correct way to get the cubic root.
I can't understand why
27 ** (1.0/3.0) #=> 3
is different from
27 ** (1/3) #=> 1
1.0 / 3.0 # => 0.3333333333333333
27 ** 0.333 # => 2.9967059728946346
1 / 3 # => 0
27 ** 0 # => 1
The second is an example of integer division. How many threes are there in one? Zero. Any number in power 0 is 1.
The first division is a decimal division and the latter is an integer division
that is 1.0/3.0 will yield a decimal result whereas 1/3will yield an integer result which in this case i 0
the results will therefor be different since it's the result of either
27**0.333...
or
27**0
which of course are clearly different.
It's enough to force one of the operators to be decimal for the entire operation to yield a decimal result e.g. 1/3.0 will yield 0.3333...
Integer division results in integers:
irb(main):004:0> 1/3
=> 0
irb(main):005:0> 1.0/3.0
=> 0.3333333333333333
27**0 = 1. 27**(1/3) = 3
(1/3) returns 0 since 3 is an integer. in ruby, if you divide using integers for both the divisor and dividend, you going to get an integer value. and since anything raised to 0 is 1, your get 1 as the answer
(1.0/3.0) returns 0.3333 since you're not dividing 2 integers so you get 3 from 27 ** 0.33...
Type conversation.
When you compute 1.0/3.0 - It is decimal
Which is 1.0/3.0 = 0.33 # which is a decimal
1/3 - It rounds to the nearest integer.
Thus:
27 ** (1.0/3.0) #=> 3
is different from
27 ** (1/3) #=> 1

Resources