Simple subtraction in Verilog - hex

I've been working on a hex calculator for a while, but seem to be stuck on the subtraction portion, particularly when B>A. I'm trying to simply subtract two positive integers and display the result. It works fine for A>B and A=B. So far I'm able use two 7-segment displays to show the integers to be subtracted and I get the proper difference as long as A>=B
When B>A I see a pattern that I'm not able to debug because of my limited knowledge in Verilog case/if-else statements. Forgive me if I'm not explaining the best way but what I'm observing is that once the first number, A, "reaches" 0 (after being subtracted from) it loops back to F. The remainder of B is then subtracted from F rather than 0.
For example: If A=1, B=3
A - B =
1 - 1 = 0
0 - 1 = F
F - 1 = E
Another example could be 4-8=C
Below are the important snippets of code I've put together thus far.
First, my subtraction statement
always#*
begin
begin
Cout1 = 7'b1000000; //0
end
case(PrintDifference[3:0])
4'b0000 : Cout0 = 7'b1000000; //0
4'b0001 : Cout0 = 7'b1111001; //1
...
4'b1110 : Cout0 = 7'b0000110; //E
4'b1111 : Cout0 = 7'b0001110; //F
endcase
end
My subtraction is pretty straightforward
output [4:0]Difference;
output [4:0] PrintDifference;
assign PrintDifference = A-B;
I was thinking I could just do something like
if A>=B, Difference = B-A
else, Difference = A-B
Thank you everyone in advance!

This is expected behaviour of twos complement addition / subtraction which I would recommend reading up on since it is so essential.
The result obtained can be changed back into an unsigned form by inverting all the bits and adding one. Checking the most significant bit will tell you if the number is negative or not.

Related

Schroders Big number sequence

I am implementing a recursive program to calculate the certain values in the Schroder sequence, and I'm having two problems:
I need to calculate the number of calls in the program;
Past a certain number, the program will generate incorrect values (I think it's because the number is too big);
Here is the code:
let rec schroder n =
if n <= 0 then 1
else if n = 1 then 2
else 3 * schroder (n-1) + sum n 1
and sum n k =
if (k > n-2) then 0
else schroder k * schroder (n-k-1) + sum n (k+1)
When I try to return tuples (1.), the function sum stops working because it's trying to return int when it has type int * int;
Regarding 2., when I do schroder 15 it returns:
-357364258
when it should be returning
3937603038.
EDIT:
firstly thanks for the tips, secondly after some hours of deep struggle, i manage to create the function, now my problem is that i'm struggling to install zarith. I think I got it installed, but ..
in terminal when i do ocamlc -I +zarith test.ml i get an error saying Required module 'Z' is unavailable.
in utop after doing #load "zarith.cma";; and #install_printer Z.pp_print;; i can compile, run the function and it works. However i'm trying to implement a Scanf.scanf so that i can print different values of the sequence. With this being said whenever i try to run the scanf, i dont get a chance to write any number as i get a message saying that '\\n' is not a decimal digit.
With this being said i will most probably also have problems with printing the value, because i dont think that i'm going to be able to print such a big number with a %d. The let r1,c1 = in the following code, is a example of what i'm talking about.
Here's what i'm using :
(function)
..
let v1, v2 = Scanf.scanf "%d %d" (fun v1 v2-> v1,v2);;
let r1,c1 = schroder_a (Big_int_Z.of_int v1) in
Printf.printf "%d %d\n" (Big_int_Z.int_of_big_int r1) (Big_int_Z.int_of_big_int c1);
let r2,c2 = schroder_a v2 in
Printf.printf "%d %d\n" r2 c2;
P.S. 'r1' & 'r2' stands for result, and 'c1' and 'c2' stands for the number of calls of schroder's recursive function.
P.S.S. the prints are written differently because i was just testing, but i cant even pass through the scanf so..
This is the third time I've seen this problem here on StackOverflow, so I assume it's some kind of school assignment. As such, I'm just going to make some comments.
OCaml doesn't have a function named sum built in. If it's a function you've written yourself, the obvious suggestion would be to rewrite it so that it knows how to add up the tuples that you want to return. That would be one approach, at any rate.
It's true, ints in OCaml are subject to overflow. If you want to calculate larger values you need to use a "big number" package. The one to use with a modern OCaml is Zarith (I have linked to the description on ocaml.org).
However, none of the other people solving this assignment have mentioned overflow as a problem. It could be that you're OK if you just solve for representable OCaml int values.
3937603038 is larger than what a 32-bit int can hold, and will therefore overflow. You can fix this by using int64 instead (until you overflow that too). You'll have to use int64 literals, using the L suffix, and operations from the Int64 module. Here's your code converted to compute the value as an int64:
let rec schroder n =
if n <= 0 then 1L
else if n = 1 then 2L
else Int64.add (Int64.mul 3L (schroder (n-1))) (sum n 1)
and sum n k =
if (k > n-2) then 0L
else Int64.add (Int64.mul (schroder k) (schroder (n-k-1))) (sum n (k+1))
I need to calculate the number of calls in the program;
...
the function 'sum' stops working because it's trying to return 'int' when it has type 'int * int'
Make sure that you have updated all the recursive calls to shroder. Remember it is now returning a pair not a number, so you can't, for example, just to add it and you need to unpack the pair first. E.g.,
...
else
let r,i = schroder (n-1) (i+1) in
3 * r + sum n 1 and ...
and so on.
Past a certain number, the program will generate incorrect values (I think it's because the number is too big);
You need to use an arbitrary-precision numbers, e.g., zarith

Counting the number of restricted Integer partitions

Original problem:
Let N be a positive integer (actually, N <= 2000) and P - set of all possible partitions of the N, where with and . Let A be the number of partitions . Find the A.
Input: N. Output: A - the number of partitions .
What have I tried:
I think that this problem can be solved by dynamic-based algorithm. Let p(n,a,b) be the function, which returns the number of partitons of n using only numbers a. . .b. Then we can compute the A with the code like:
int Ans = 2; // the 1+1+...+1=N & N=N partitions
for(int a = 2; a <= N/2; a += 1){ //a - from 2 to N/2
int b = a*2-1;
Ans += p[N][a][b]; // add all partitions using a..b to Answer
if(a < (a-1)*2-1){ // if a < previous b [ (a-1)*2-1 ]
Ans -= p[N][a][(a-1)*2-1]; // then we counted number of partitions
} // using numbers a..prev_b twice.
}
Next I tried to find the dynamic algorithm computing p(n,a,b) for any integer a <= b <= n. This paper (.pdf) provides the folowing algorithm:
, were I(n<=b) = 1 if n<=b and =0 otherwise.
Question(s):
How should I realize the algorithm from the paper? I'm new at d-p problems and as I can see, this problem has 3 dimensions (n,a & b), which is quite tricky for me.
How actually that algorithm works? I know how work the algorithms for computing p(n,0,b) or p(n,a,n), but a little explanation for p(n,a,b) will be very helpful.
Does original problem have simpler solution? I'm quite sure that there's another clean solution, but I didn't found it.
I calculated all A(1)-A(600) in 23 seconds with memoization approach (top-down dynamic programming). 3D table requires 1.7 GB of memory.
For reference: A[50] = 278, A(200)=465202, A(600)=38860513616
N=2000 requires too large table for 32-bit environment, and map approach worked too slow.
I can make 2D table with reasonable size, but this approach requires table zeroing at every iteration of external loop - slow again.
A(1000) = 107292471486730 in 131 sec. And I think that long arithmetic might be needed for larger values to avoid Int64 overflow.

F#: integer (%) integer - Is Calculated How?

So in my text book there is this example of a recursive function using f#
let rec gcd = function
| (0,n) -> n
| (m,n) -> gcd(n % m,m);;
with this function my text book gives the example by executing:
gcd(36,116);;
and since the m = 36 and not 0 then it ofcourse goes for the second clause like this:
gcd(116 % 36,36)
gcd(8,36)
gcd(36 % 8,8)
gcd(4,8)
gcd(8 % 4,4)
gcd(0,4)
and now hits the first clause stating this entire thing is = 4.
What i don't get is this (%)percentage sign/operator or whatever it is called in this connection. for an instance i don't get how
116 % 36 = 8
I have turned this so many times in my head now and I can't figure how this can turn into 8?
I know this is probably a silly question for those of you who knows this but I would very much appreciate your help the same.
% is a questionable version of modulo, which is the remainder of an integer division.
In the positive, you can think of % as the remainder of the division. See for example Wikipedia on Euclidean Divison. Consider 9 % 4: 4 fits into 9 twice. But two times four is only eight. Thus, there is a remainder of one.
If there are negative operands, % effectively ignores the signs to calculate the remainder and then uses the sign of the dividend as the sign of the result. This corresponds to the remainder of an integer division that rounds to zero, i.e. -2 / 3 = 0.
This is a mathematically unusual definition of division and remainder that has some bad properties. Normally, when calculating modulo n, adding or subtracting n on the input has no effect. Not so for this operator: 2 % 3 is not equal to (2 - 3) % 3.
I usually have the following defined to get useful remainders when there are negative operands:
/// Euclidean remainder, the proper modulo operation
let inline (%!) a b = (a % b + b) % b
So far, this operator was valid for all cases I have encountered where a modulo was needed, while the raw % repeatedly wasn't. For example:
When filling rows and columns from a single index, you could calculate rowNumber = index / nCols and colNumber = index % nCols. But if index and colNumber can be negative, this mapping becomes invalid, while Euclidean division and remainder remain valid.
If you want to normalize an angle to (0, 2pi), angle %! (2. * System.Math.PI) does the job, while the "normal" % might give you a headache.
Because
116 / 36 = 3
116 - (3*36) = 8
Basically, the % operator, known as the modulo operator will divide a number by other and give the rest if it can't divide any longer. Usually, the first time you would use it to understand it would be if you want to see if a number is even or odd by doing something like this in f#
let firstUsageModulo = 55 %2 =0 // false because leaves 1 not 0
When it leaves 8 the first time means that it divided you 116 with 36 and the closest integer was 8 to give.
Just to help you in future with similar problems: in IDEs such as Xamarin Studio and Visual Studio, if you hover the mouse cursor over an operator such as % you should get a tooltip, thus:
Module operator tool tip
Even if you don't understand the tool tip directly, it'll give you something to google.

Base conversion error in matlab code

I created the following simple matlab functions to convert a number from an arbitrary base to decimal and back
this is the first one
function decNum = base2decimal(vec, base)
decNum = vec(1);
for d = 1:1:length(vec)-1
decNum = decNum*base + vec(d+1);
end
and here is the other one
function baseNum = decimal2base(num, base, Vlen)
ii = 1;
if num == 0
baseNum = 0;
end
while num ~= 0
baseNum(ii) = mod(num, base);
num = floor(num./base);
ii = ii+1;
end
baseNum = fliplr(baseNum);
if Vlen>(length(baseNum))
baseNum = [zeros(1,(Vlen)-(length(baseNum))) baseNum ];
end
Due to the fact that there are limitations to how big a number can be these functions can't successfully convert vary big vectors, but while testing them I noticed the following bug
Let's use the following testing function
num = 201;
pCount = 7
x=base2decimal(repmat(num-1, 1, pCount), num)
repmat(num-1, 1, pCount)
y=decimal2base(x, num, 1)
isequal(repmat(num-1, 1, pCount),y)
A supposed vector with seven (7) digits in base201 works fine, but the same vector with base200 does not return the expected result even though it is smaller and theoretically should be converted successfully.
(One preliminary comment: calling base2decimal won't result in a decimal number but rather in a number :-D)
This is due floating-point limited precision (in our case, double). To test it, just type at the MATLAB Command Window:
>> 200^7 - 1 == 200^7
ans =
1
>> mod(200^7 - 1, 200)
ans =
0
which means that the value of your number in base 200 (which is precisely 2007−1) is represented exactly as 2007, and the "true" value of representation is 2007.
On the other hand:
>> 201^7 - 1 == 201^7
ans =
1
so still the two numbers are represented the same, but
>> mod(201^7 - 1, 201)
ans =
200
which means that the two values share the "true" representation of 2017−1, which, by accident, is the value that you expected.
TL;DR
When stored in a double, 2007−1 is inaccurately represented as 2007, while 2017−1 is accurately represented.
"Bigger numbers are less accurately represented than smaller numbers" is a misconception: if it was true, there would be no big numbers that could be exactly represented.
Judging from your own observations:
The code works fine in most cases
The code can give small errors for large numbers
The suspect is apparent:
Rounding issues seem to give you headaces here. This is also illustrated by #RTL in the comments.
The first question should now be:
1. Do you need perfect accuracy for such large numbers? Or is it ok if it is off by a relatively small amount sometimes?
If that is answered with a yes, I would recommend you to try a different storage format.
The simple solution would be to use big integers:
uint64
The alternative would be to make your own storage format. This is required if you need even bigger numbers. I think you can cover a huge range with a cell array and some tricks, but of course it is going to be hard to combine those numbers afterwards without losing the accuracy that you worked so hard for.

Why is 0 divided by 0 an error?

I have come across this problem in a calculation I do in my code, where the divisor is 0 if the divident is 0 too. In my code I return 0 for that case. I am wondering, while division by zero is generally undefined, why not make an exception for this case? My understanding why division by zero is undefined is basically that it cannot be reversed. However, I do not see this problem in the case 0/0.
EDIT OK, so this question spawned a lot of discussion. I made the mistake of over-eagerly accepting an answer based on the fact that it received a lot of votes. I now accepted AakashM's answer, because it provides an idea on how to analyze the problem.
Let's say:
0/0 = x
Now, rearranging the equation (multiplying both sides by 0) gives:
x * 0 = 0
Now do you see the problem? There are an infinite number of values for x as anything multiplied by 0 is 0.
This is maths rather than programming, but briefly:
It's in some sense justifiable to assign a 'value' of positive-infinity to some-strictly-positive-quantity / 0, because the limit is well-defined
However, the limit of x / y as x and y both tend to zero depends on the path they take. For example, lim (x -> 0) 2x / x is clearly 2, whereas lim (x -> 0) x / 5x is clearly 1/5. The mathematical definition of a limit requires that it is the same whatever path is followed to the limit.
(Was inspired by Tony Breyal's rather good answer to post one of my own)
Zero is a tricky and subtle beast - it does not conform to the usual laws of algebra as we know them.
Zero divided by any number (except zero itself) is zero. Put more mathematically:
0/n = 0 for all non-zero numbers n.
You get into the tricky realms when you try to divide by zero itself. It's not true that a number divided by 0 is always undefined. It depends on the problem. I'm going to give you an example from calculus where the number 0/0 is defined.
Say we have two functions, f(x) and g(x). If you take their quotient, f(x)/g(x), you get another function. Let's call this h(x).
You can also take limits of functions. For example, the limit of a function f(x) as x goes to 2 is the value that the function gets closest to as it takes on x's that approach 2. We would write this limit as:
lim{x->2} f(x)
This is a pretty intuitive notion. Just draw a graph of your function, and move your pencil along it. As the x values approach 2, see where the function goes.
Now for our example. Let:
f(x) = 2x - 2
g(x) = x - 1
and consider their quotient:
h(x) = f(x)/g(x)
What if we want the lim{x->1} h(x)? There are theorems that say that
lim{x->1} h(x) = lim{x->1} f(x) / g(x)
= (lim{x->1} f(x)) / (lim{x->1} g(x))
= (lim{x->1} 2x-2) / (lim{x->1} x-1)
=~ [2*(1) - 2] / [(1) - 1] # informally speaking...
= 0 / 0
(!!!)
So we now have:
lim{x->1} h(x) = 0/0
But I can employ another theorem, called l'Hopital's rule, that tells me that this limit is also equal to 2. So in this case, 0/0 = 2 (didn't I tell you it was a strange beast?)
Here's another bit of weirdness with 0. Let's say that 0/0 followed that old algebraic rule that anything divided by itself is 1. Then you can do the following proof:
We're given that:
0/0 = 1
Now multiply both sides by any number n.
n * (0/0) = n * 1
Simplify both sides:
(n*0)/0 = n
(0/0) = n
Again, use the assumption that 0/0 = 1:
1 = n
So we just proved that all other numbers n are equal to 1! So 0/0 can't be equal to 1.
walks on back to her home over at mathoverflow.com
Here's a full explanation:
http://en.wikipedia.org/wiki/Division_by_zero
( Including the proof that 1 = 2 :-) )
You normally deal with this in programming by using an if statement to get the desired behaviour for your application.
The problem is with the denominator. The numerator is effectively irrelevant.
10 / n
10 / 1 = 10
10 / 0.1 = 100
10 / 0.001 = 1,000
10 / 0.0001 = 10,000
Therefore: 10 / 0 = infinity (in the limit as n reaches 0)
The Pattern is that as n gets smaller, the results gets bigger. At n = 0, the result is infinity, which is a unstable or non-fixed point. You can't write infinity down as a number, because it isn't, it's a concept of an ever increasing number.
Otherwise, you could think of it mathematically using the laws on logarithms and thus take division out of the equation altogther:
log(0/0) = log(0) - log(0)
BUT
log(0) = -infinity
Again, the problem is the the result is undefined because it's a concept and not a numerical number you can input.
Having said all this, if you're interested in how to turn an indeterminate form into a determinate form, look up l'Hopital's rule, which effectively says:
f(x) / g(x) = f'(x) / g'(x)
assuming the limit exists, and therefore you can get a result which is a fixed point instead of a unstable point.
Hope that helps a little,
Tony Breyal
P.S. using the rules of logs is often a good computational way to get around the problems of performing operations which result in numbers which are so infinitesimal small that given the precision of a machine’s floating point values, is indistinguishable from zero. Practical programming example is 'maximum likelihood' which generally has to make use of logs in order to keep solutions stable
Look at division in reverse: if a/b = c then c*b = a. Now, if you substitute a=b=0, you end up with c*0 = 0. But ANYTHING multiplied by zero equals zero, so the result can be anything at all. You would like 0/0 to be 0, someone else might like it to be 1 (for example, the limiting value of sin(x)/x is 1 when x approaches 0). So the best solution is to leave it undefined and report an error.
You may want to look at Dr. James Anderson's work on Transarithmetic. It isn't widely accepted.
Transarithmetic introduces the term/number 'Nullity' to take the value of 0/0, which James likens to the introduction 'i' and 'j'.
The structure of modern math is set by mathematicians who think in terms of axioms.
Having additional axioms that aren't productive and don't really allow one to do more stuff is against the ideal of having clear math.
How many times does 0 go into 0? 5. Yes - 5 * 0 = 0, 11. Yes - 11 * 0 = 0, 43. Yes - 43 * 0 = 0. Perhaps you can see why it's undefined now? :)
Since x/y=z should be equivalent to x=yz, and any z would satisfy 0=0z, how useful would such an 'exception' be?
Another explanation of why 0/0 is undefined is that you could write:
0/0 = (4 - 4)/0 = 4/0 - 4/0
And 4/0 is undefined.
If a/b = c, then a = b * c.
In the case of a=0 and b=0, c can be anything because 0 * c = 0 will be true for all possible values of c. Therefore, 0/0 is undefined.
This is only a Logical answer not a mathamatical one,
imagine Zero as empty how can you Divide an empty by an empty this is the case in division by zero also how can you divide by something which is empty.
0 means nothing, so if you have nothing, it does not imply towards anything to distribute to anything. Some Transit Facilities when they list out the number of trips of a particular line, trip number 0 is usually the special route that is routed in a different way. Typically, a good example would be in the Torrance Transit Systems where Line 2 has a trip before the first trip known as trip number 0 that operates on weekdays only, that trip in particular is trip number 0 because it is a specialized route that is routed differently from all the other routes.
See the following web pages for details:
http://transit.torrnet.com/PDF/Line-2_MAP.pdf
http://transit.torrnet.com/PDF/Line-2_Time_PDF.pdf
On the map, trip number 0 is the trip that is mapped in dotted line, the solid line maps the regular routing.
Sometimes 0 can be used on numbering the trips a route takes where it is considered the "Express Service" route.
why not make an exception for this
case?
Because:
as others said, it's not that easy;)
there's no application for defining 0/0 - adding exception would complicate mathematics for no gains.
This is what I'd do:
function div(a, b) {
if(b === 0 && a !== 0) {
return undefined;
}
if(b === 0 && a === 0) {
return Math.random;
}
return a/b;
}
When you type in zero divided by zero, there's an error because whatever you multiply zero from will be zero so it could be any number.
As Andrzej Doyle said:
Anything dived by zero is infinity. 0/0 is also infinity. You can't get 0/0 = 1. That's the basic principle of maths. That's how the whole world goes round. But you can sure edit a program to say "0/0 is not possible" or "Cannot divide by zero" as they say in cell phones.

Resources