trying to mimic the verilog behavior regarding the bitwise operations (meaning - an operation that works on all bits of a vector and output 1 bit answer.
example:
use ieee.std_logic_1164.all;
use ieee.std_logic_unsigned.all;
...
signal vect : std_logic_vector (length -1 downto 0);
signal ans : std_logic;
signal addin : std_logic;
when vect = all '0' i will want ans to be '1' (nor)
when vect = all '1' i will want ans to be '1' (and)
when vect = even num of '1' i will want ans to be '1' (xor)
, etc.
i made the following functions (only one is shown here):
function vand (vect :std_logic_vector) return std_logic is
variable temp : std_logic;
begin
temp := '1';
for I in (vect'length -1) downto 0 loop
temp := temp and vect(I);
end loop;
return temp;
end;
this function should give the "AND" on all bits.
so, here comes my questions:
a. is there an easier way to make such operations?
b. i'm using Vand like this if Vand(vect & addin) = '1' do something... but when vect is '0H' and addin is 'H' the condition is filled and I have no idea why. can someone think why this kind of operation is problematic? the function behaves itself on other cases, but here i tested it for rapid change immunity and got this unwanted behavir.
edit
i do not know the length of the vector 'vect' or the vector 'vect & addin'.
edit 2
solved the second problem by creating a sub function Vand(vect : std_logic_vector; b: std_logic) that uses the original Vand (and found a bug in my Vnor along the way). still hoping for a better solution than these two functions.
There are functions called or_reduce and and_reduce which do what you want. They also call to_X01 on the inputs, which means that H and Ls will be converted to 1 and 0.
They can be found in std_logic_misc for std_logic_vectors and are proposed for the next rev of VHDL for ieee.numeric_std for signed and unsigned vectors.
VHDL-2008 also allows this syntax on std_logic_vectors:
anded <= and v;
ored <= or v;
Related
I'm currently learning about recursion, it's pretty hard to understand. I found a very common example for it:
function factorial(N)
local Value
if N == 0 then
Value = 1
else
Value = N * factorial(N - 1)
end
return Value
end
print(factorial(3))
N == 0 is the base case. But when i changed it into N == 1, the result is still remains the same. (it will print 6).
Is using the base case important? (will it break or something?)
What's the difference between using N == 0 (base case) and N == 1?
That's just a coincidence, since 1 * 1 = 1, so it ends up working either way.
But consider the edge-case where N = 0, if you check for N == 1, then you'd go into the else branch and calculate 0 * factorial(-1), which would lead to an endless loop.
The same would happen in both cases if you just called factorial(-1) directly, which is why you should either check for > 0 instead (effectively treating every negative value as 0 and returning 1, or add another if condition and raise an error when N is negative.
EDIT: As pointed out in another answer, your implementation is not tail-recursive, meaning it accumulates memory for every recursive functioncall until it finishes or runs out of memory.
You can make the function tail-recursive, which allows Lua to treat it pretty much like a normal loop that could run as long as it takes to calculate its result:
local function factorial(n, acc)
acc = acc or 1
if n <= 0 then
return acc
else
return factorial(n-1, acc*n)
end
return Value
end
print(factorial(3))
Note though, that in the case of factorial, it would take you way longer to run out of stack memory than to overflow Luas number data type at around 21!, so making it tail-recursive is really just a matter of training yourself to write better code.
As the above answer and comments have pointed out, it is essential to have a base-case in a recursive function; otherwise, one ends up with an infinite loop.
Also, in the case of your factorial function, it is probably more efficient to use a helper function to perform the recursion, so as to take advantage of Lua's tail-call optimizations. Since Lua conveniently allows for local functions, you can define a helper within the scope of your factorial function.
Note that this example is not meant to handle the factorials of negative numbers.
-- Requires: n is an integer greater than or equal to 0.
-- Effects : returns the factorial of n.
function fact(n)
-- Local function that will actually perform the recursion.
local function fact_helper(n, i)
-- This is the base case.
if (i == 1) then
return n
end
-- Take advantage of tail calls.
return fact_helper(n * i, i - 1)
end
-- Check for edge cases, such as fact(0) and fact(1).
if ((n == 0) or (n == 1)) then
return 1
end
return fact_helper(n, n - 1)
end
The following example in Pascal was given in a book dedicated to the basics of programming. The function ReadLongint is supposed to check whether the input is 0-9 encoded in a char type. The function then returns true or false depending on the check results, as well as a variable for calculations, rendered into an integer via the operator ord().
Being a newbie I've had hard times figuring out how exactly this code works. But even the bigger mystery for me was the necessity of line 9.
'repeat
read(c);
position := position + 1;
until (c <> #32) and (c <> #10);'
I can see that it's a cycle which repeats itself if you input Space or Enter. However, I've checked the program without these lines, substituting it with a simple read(c); , and the program seems to work just fine. Can somebody please explain the role of this line in the example?
Here is the full program:
function ReadLongint(var check: longint): boolean;
var
c: char;
number: longint;
position: integer;
begin
number := 0;
position := 0;
repeat
read(c);
position := position + 1;
until (c <> #32) and (c <> #10);
while (c <> #32) and (c <> #10) do
begin
if (c < '0') or (c > '9') then
begin
writeln('Unexpected ''', c, ''' in position: ', position);
readln;
ReadLongint := false;
exit
end;
number := number * 10 + ord(c) - ord('0');
read(c);
position := position + 1
end;
check := number;
ReadLongint := true
end;
var
x, y: longint;
ok: boolean;
begin
repeat
write('Please type the first number: ');
ok := ReadLongint(x)
until ok = true;
repeat
write('Please type the second number: ');
ok := ReadLongint(y)
until ok = true;
writeln(x, ' times ', y, ' is ', x * y)
end.
Your readLongInt function wants to (partially) mimic the behavior of read/readLn. The behavior of read/readLn differs slightly if the destination variable is an integer (or real) or char value. The ISO Standard 7185 puts it like that:
c) If v is a variable-access possessing the integer-type (or subrange thereof), read(f, v) shall satisfy the following requirements. No component of s shall equal end‑of‑line. The components of r, if any, shall each, and (s ~t ~u).first shall not, equal either the char-type value space or end‑of‑line. […]
Translated to plain English: Leading spaces and newlines are ignored when interpreting a number (i. e. an integer [or real] variable as the destination). This is quite different to read/readLn in conjunction with a char‑variable where ' ' is a legal value, thus it is not “skipped”, you know.
The until (c <> #32) and (c <> #10) loop is trying to imitate the behavior of read(check) although the actually used read(c) merely reads a single char value, one after another.
PS: It always makes me cringe seeing ok = true. I hope you, unlike the author(s) of the textbook, knows that the = true is redundant, merely an identity.
Unlike Matlab, Octave Symbolic has no piecewise function. Is there a work around? I would like to do something like this:
syms x
y = piecewise(x0, 1)
Relatedly, how does one get pieces of a piecewise function? I ran the following:
>> int (exp(-a*x), x, 0, t)
And got the following correct answer displayed and stored in a variable:
t for a = 0
-a*t
1 e
- - ----- otherwise
a a
But now I would like to access the "otherwise" part of the answer so I can factor it. How do I do that?
(Yes, I can factor it in my head, but I am practicing for when more complicated expressions come along. I am also only really looking for an approach using symbolic expressions -- even though in any single case numerics may work fine, I want to understand the symbolic approach.)
Thanks!
Matlab's piecewise function seems to be fairly new (introduced in 2016b), but it basically just looks like a glorified ternary operator. Unfortunately I don't have 2016 to check if it performs any checks on the inputs or not, but in general you can recreate a 'ternary' operator in octave by indexing into a cell using logical indexing. E.g.
{#() return_A(), #() return_B(), #() return_default()}([test1, test2, true]){1}()
Explanation:
Step 1: You put all the values of interest in a cell array. Wrap them in function handles if you want to prevent them being evaluated at the time of parsing (e.g. if you wanted the output of the ternary operator to be to produce an error)
Step 2: Index this cell array using logical indexing, where at each index you perform a logical test
Step 3: If you need a 'default' case, use a 'true' test for the last element.
Step 4: From the cell (sub)array that results from above, select the first element and 'run' the resulting function handle. Selecting the first element has the effect that if more than one tests succeed, you only pick the first result; given the 'default' test will always succeed, this also makes sure that this is not picked unless it's the first and only test that succeeds (which it does so by default).
Here are the above steps implemented into a function (appropriate sanity checks omitted here for brevity), following the same syntax as matlab's piecewise:
function Out = piecewise (varargin)
Conditions = varargin(1:2:end); % Select all 'odd' inputs
Values = varargin(2:2:end); % Select all 'even' inputs
N = length (Conditions);
if length (Values) ~= N % 'default' case has been provided
Values{end+1} = Conditions{end}; % move default return-value to 'Values'
Conditions{end} = true; % replace final (ie. default) test with true
end
% Wrap return-values into function-handles
ValFuncs = cell (1, N);
for n = 1 : N; ValFuncs{n} = #() Values{n}; end
% Grab funhandle for first successful test and call it to return its value
Out = ValFuncs([Conditions{:}]){1}();
end
Example use:
>> syms x t;
>> F = #(a) piecewise(a == 0, t, (1/a)*exp(-a*t)/a);
>> F(0)
ans = (sym) t
>> F(3)
ans = (sym)
-3⋅t
ℯ
─────
9
I'm new to Julia.
I mainly program in python.
In python,
if you want to iterate over a large set of values,
it is typical to construct a so-called generator to save memory usage.
Here is one example code:
def generator(N):
for i in range(N):
yield i
I wonder if there is anything alike in Julia.
After reading julia manual,
#task macro seems to have the same (or similar) functionality as generator in python.
However,
after some experiments,
the memory usage seems to be larger than usual array in julia.
I use #time in IJulia to see the memory usage.
Here is my sample code:
[Update]: Add the code for generator method
(The generator method)
function generator(N::Int)
for i in 1:N
produce(i)
end
end
(generator version)
function fun_gener()
sum = 0
g = #task generator(100000)
for i in g
sum += i
end
sum
end
#time fun_gener()
elapsed time: 0.420731828 seconds (6507600 bytes allocated)
(array version)
function fun_arry()
sum = 0
c = [1:100000]
for i in c
sum += i
end
sum
end
#time fun_arry()
elapsed time: 0.000629629 seconds (800144 bytes allocated)
Could anyone tell me why #task will require more space in this case?
And if I want to save memory usage as dealing with a large set of values,
what can I do?
I recommend the "tricked out iterators" blogpost by Carl Vogel, which discusses julia's iterator protocol, tasks and co-routines in some detail.
See also task-aka-coroutines in the julia docs.
In this case you should use the Range type (which defines an iterator protocol):
julia> function fun_arry()
sum = 0
c = 1:100000 # remove the brackets, makes this a Range
for i in c
sum += i
end
sum
end
fun_arry (generic function with 1 method)
julia> fun_arry() # warm up
5000050000
julia> #time fun_arry()
elapsed time: 8.965e-6 seconds (192 bytes allocated)
5000050000
Faster and less memory allocated (just like xrange in python 2).
A snippet from the blogpost:
From https://github.com/JuliaLang/julia/blob/master/base/range.jl, here’s how a Range’s iterator protocol is defined:
start(r::Ranges) = 0
next{T}(r::Range{T}, i) = (oftype(T, r.start + i*step(r)), i+1)
next{T}(r::Range1{T}, i) = (oftype(T, r.start + i), i+1)
done(r::Ranges, i) = (length(r) <= i)
Notice that the next method calculates the value of the iterator in state i. This is different from an Array iterator, which just reads the element a[i] from memory.
Iterators that exploit delayed evaluation like this can have important performance benefits. If we want to iterate over the integers 1 to 10,000, iterating over an Array means we have to allocate about 80MB to hold it. A Range only requires 16 bytes; the same size as the range 1 to 100,000 or 1 to 100,000,000.
You can write a generator method (using Tasks):
julia> function generator(n)
for i in 1:n # Note: we're using a Range here!
produce(i)
end
end
generator (generic function with 2 methods)
julia> for x in Task(() -> generator(3))
println(x)
end
1
2
3
Note: if you replace the Range with this, the performance is much poorer (and allocates way more memory):
julia> #time fun_arry()
elapsed time: 0.699122659 seconds (9 MB allocated)
5000050000
This question was asked (and answered) quite a while ago. Since this question is ranked high on google searches, I'd like to mention that both the question and answer are outdated.
Nowadays, I'd suggest checking out https://github.com/BenLauwens/ResumableFunctions.jl for a Julia library with a macro that implements Python-like yield generators.
using ResumableFunctions
#resumable function fibonnaci(n::Int) :: Int
a = 0
b = 1
for i in 1:n-1
#yield a
a, b = b, a+b
end
a
end
for fib in fibonnaci(10)
println(fib)
end
Since its scope is much more limited than full coroutines, it is also an order of magnitude more efficient than pushing values into a channel since it can compile the generator into a FSM. (Channels have replaced the old produce() function mentioned in the question and previous answers).
With that said, I'd still suggest pushing into a channel as your first approach if performance isn't an issue, because resumablefunctions can sometimes be finicky when compiling your function and can occasionally hit some worst-case behaviour. In particular, because it is a macro that compiles to an FSM rather than a function, you currently need to annotate the types of all variables in the Resumablefunction to get good performance, unlike vanilla Julia functions where this is handled by JIT when the function is first called.
I think that Task has been superseded by Channel(). The usage in terms of Ben Lauwens's Fibonacci generator is:
fibonacci(n) = Channel(ctype=Int) do c
a = 1
b = 1
for i in 1:n
push!(c, a)
a, b = b, a + b
end
end
it can be used using
for a in fibonacci(10)
println(a)
end
1
1
2
3
5
8
13
21
34
55
Is there a way in matlab to restrict variables in a function
For example i have a function
function S0 = S0Func(obj, c, delta, xT, sigma)
beta = obj.betaFunc(sigma);
xb = obj.xbFunc(c, delta, sigma);
S0 = (1-obj.tau).*(obj.x0./(obj.r-obj.mu)-c./obj.r-(xb./(obj.r-obj.mu)-c./obj.r).*((obj.x0./xb).^beta)-((delta-1).*c./obj.r).*((obj.x0./xT).^beta-((obj.x0./xb).^beta)));
end
where I would like to have the restrictions (obj is an object of a class)
0<xb<xT<1
0<c
1<delta
What I would like to do is to draw a 3d graph of the following with the restrictions mentioned above
S0Func(2.7, 1, 1, 0.3)-S0Func(c,delta,xT,0.2)<0;
EDIT
I have tried using the isosurface
optimalStraightCoupon = fminbnd(#(c) -(S0Function(c,1,1)+D0Function(c,1,1)), 0, 4);
[xT, delta, c] = meshgrid(0.8:.01:1, 1:.1:3, 0:.1:4);
values = S0Function(optimalStraightCoupon,1, 1)- S0Function(c,delta, xT);
patch(isosurface(xT, c, delta, values, 1), 'FaceColor', 'red');
view(3);
I get some output, but it is not correct as the restriction on xT is violated.
Any help is appreciated. Thank you.
It's a little unclear what you are trying to achieve. I expect that you know that you can write statements such as (pseudocode):
if c>=0 exit
which, in a sense, restricts your function to operate only on values which meet the defined constraints.
The foregoing is so simple that I am sure that I have misunderstood your question.
No, it appears you wish MORE than a just 3-d graph. It appears you wish to see this function as a FUNCTION of three variables: c, delta, xT. So a 4-d graph. In that event, you will need to simply evaluate the function over a 3-d mesh (using meshgrid or ndgrid to generate the points.)
Then use isosurface to visualize the result, as essentially a higher dimensional contour plot. Do several such plots, at different iso-levels.
I would just return NaN when your constraints are violated.
Just add following lines to your function (preferable before the calculation to save time)
if delta <= 1 || c <= 0 || ... % I assume you can write them yourself
S0 = NaN;
return
end
Plot will not draw NaNs.
Though as you input c,delta,xT it's the question why they are set to invalid values in the first place. You could save some checks and therefore time if you assure that beforehand.