this is my first Scilab algorithm (Horner's method). Please tell me what should I correct to make it working (according to this flowchart). I am a very beginner. Your feedback will be highly appreciated. Thanks!
function
N=4 //number of elements
TAB=[4,2,6,5] //exemplary numbers
w=a0
i=1
while i<=n do
w=wx+a[i]
i=i+1
end
endfunction
Please, read some introduction (https://www.scilab.org/scilab-real-dummies for example) to Scilab to learn the basics it will help you for the future.
The calling sequence of your function should be something like:
v=myhorner(A,x)
where A is the array containing the polynomial coefficients in decreasing order and x the value for which you want to evaluate the polynomial.
Then the code should be
v=A(1);
for i=2:size(A,"*")
v=v*x+A(i);
end
Note however the horner function already exists in Scilab
Related
I have some confusion in:
for i = 1 to n
does this pseudocode code means for(i=1; i<n; i++) or for(i=1; i<=n; i++) ?
And if one from them, then what will be the pseudocode for another one?
It should be understood to include an iteration where i takes the value of n.
However, there are no strict rules for pseudo code, and so in case there is doubt about an actual piece of pseudo code, then this means that code didn't achieve what it was supposed to do: unambiguously describe an algorithm without any programming language in mind.
Here are some of the arguments why it should be understood to include n:
When in plain English we tell someone to count from 1 "to 100", we mean that they should include 100 at the end. This is probably the strongest argument.
I know of no programming language that uses the to keyword in a for loop syntax, where the value that follows to is not to be included in the iterations. On the other hand, BASIC like languages (such as vba) have that syntax, and the "to" value will be used for the final iteration.
On Wikipedia some examples of pseudo code loops are given, and where the to keyword is used, the final iteration is using that value.
If the intention of this loop is to visit each value in an array of n elements (a very common case), then there is no ambiguity: for i = 1 to n tells us that the array's first element has position 1, and hence its last position is position n. It is not uncommon to use such 1-based indexing of arrays in pseudo code, as this is more intutive to non-programmers. If however in such array context you see for i = 0 to n in pseudo code, some alarms should go off. That definitely would come across ambiguous.
It is highly contextual and depends on the person who wrote it. (It also kind of depends on the programming language that the pseudocode is aimed to be converted to.)
If it were in an interview setting, it might be a good idea to ask if this is "inclusive of n or not". Because it could be either case.
(I know this answer might not be that helpful. Sorry about that, but it doesn't seem that this has a definitive answer.)
I have developed a recursive formula for knapsack problem on my own without any knowledge of present solutions. Please tell me whether it is right or wrong and correct it.Thanks in advance.
B(S) = max (B (s-w(i)) + b(w(i)) )
for all i belonging to n;
notations are as usual . S is capacity,B is the answer to knapsack.
I do not want to give you straight answer, but to direct you on the flaws of your formula, and let you figure out how to solve them.
Well, if you do not address the value, something must be wrong - otherwise, you just simply lose information. If you chose to "take" the item (B(s-w(i))) what happens to the current value?
In addition, what is i? How do you change i over time?
When talking about recursive formula, you must also mention a stop clause for it.
We know that if $μ(n)=0$ then the integer n has at least one factor with multiplicity.
Now how can we determine if in the decomposition of a rational (m/n)>1 to prime factors, we have a power less than (-1)? For example
m=2*3*5*7*11;
n=2^2*3^3*5;
m/n=2^(-1)*3^(-2)*7*11
f(m/n)=0 (*for example*)
Is there any function similar to Moebius function μ in Mathematica which does this job for me?
I think I can write the code, but I need a defined function in Mathematica?
thanks
I think I found it,
It should be
f[x_]:=If[SquareFreeQ[x]==True,1,0]
I am sorry if I sound stupid or vague, but I have a question regarding a code about Bessel functions. I was tasked with the homework of representing a simple function, (f(x)=1-x to be exact) using the first five 0th order Bessel functions whos zeros are scaled to one. Plus I have to find their coefficients.
First off, I know I have to show that I've worked on this problem before asking for help, but I really don't know where to begin. I know about first-order Bessel functions and I know about second-order Bessel functions, but I have no idea what a 0th order Bessel function is. Plus, I didn't even know you could represent functions with Bessel functions. I know that you can use Taylor's expansion or Fourier representation to approximate a function, but I have no idea how to do that with the Bessel function. I searched this website and it seems a classmate of mine, rather rudely, just copy and pasted our assignment and thus that thread was closed.
So if some saintly person could at least point me in the right direction here, that would be wonderful. Seeing as this is a simple function and I know that Matlab has a Bessel function thing so coding it wouldn't be too hard. I just don't know how to use a method of solving a differential equation to represent another function. Oh, and the coefficients? What coefficients? Forgive my ignorance and help please!
Alright! Through much investigation and work, I have determined the answer to this problem. Now, this is actually the first time that I'm answering a question on this site, so once more, please forgive any faux pax that I might commit.
First off, it appears that I was right about the Bessel-Fourier series. It is impossible to use just the Bessel series to get a function approximation. Through a lengthy process starting with the Bessel function and scaling the x and doing a whole host of tricks that include a Fourier transform, we get can determine that the Bessel-Fourier representation of a function is given in the form of
f(x) = A1*J_0(z1x) + A2*J_0(z2x) + ....
where z1 are the zeros of a First-Order Bessel Function, J_0 is the 0th First-Order Bessel Function and A1 are the coefficients of the Fourier-Bessel series. The zeros are easily acquired by just plotting the Bessel Function, but the coefficients are the tricky parts. They are given by the equation
An = (2/(J_1(zn)^2))*integral(x*f(x)*J_0(zn*x), 0, 1)
Needless to say, the difficult part of this is getting the integral of the Bessel functions. But by using this lovely list, the process can be made simple. Messy....but simple. I should also note that the the integral is from 0 to 1 because that was the nature of my assignment. If the question was to scale it from 0 to 2, then the equation would be
An = (2/(2^2)*(J_1(zn)^2))*integral(x*f(x)*J_0(zn*x), 0, 2)
But I digress. So, since my assignment also had me graph the first five values individually, and then add them together and compare the results with the actual function, that's what I did. And thus here is the code.
%%Plotting the Bessel Functions
a=[2.40483, 5.52008, 8.65373, 11.7915, 14.9309]; %a matrix with the first 5 zeros for a first order Bessle Function
A=zeros(5,1);
F=zeros(1, 100);
X=linspace(0,1);
for i=1:1:5
A(i,1)= (2*(besselj(1,a(i))*struve(0,a(i))-besselj(0,a(i))*struve(1,a(i))))/((a(i)^2)*(besselj(1,a(i)))^2)*(3.14/2);
%the equation to determine the coefficients of the Bessel-Fourier series
end
for i=1:1:5
figure(i);
plot(X, A(i,1)*besselj(0, (a(i)*X))); %plot the first 5 Bessel functions
end
for i=1:1:5
F=F+A(i,1)*besselj(0, (a(i)*X)); %adding all the Bessel functions together
end
figure(6);
plot(X, F); %plotting the Bessel functions and 1-x
hold on
plot(X, 1-X);
%%Struve Function
function f=struve(v,x,n)
% Calculates the Struve Function
%
% struve(v,x)
% struve(v,x,n)
%
% H_v(x) is the struve function and n is the length of
% the series calculation (n=100 if unspecified)
%
% from: Abramowitz and Stegun: Handbook of Mathematical Functions
% http://www.math.sfu.ca/~cbm/aands/page_496.htm
if nargin<3
n=100;
end
k=0:n;
x=x(:)';
k=k(:);
xx=repmat(x,length(k),1);
kk=repmat(k,1,length(x));
TOP=(-1).^kk;
BOT=gamma(kk+1.5).*gamma(kk+v+1.5);
RIGHT=(xx./2).^(2.*kk+v+1);
FULL=TOP./BOT.*RIGHT;
f=sum(FULL);
And there we go. The struve function code was from this place
I hope this helped, and if I made any egregious errors, please tell me, but to be honest, I can't explain the equations up there any further as I just got them from a textbook.
Best wishes!
This question already has answers here:
Closed 13 years ago.
Possible Duplicates:
Is there a problem that has only a recursive solution?
Can every recursion be converted into iteration?
“Necessary” Uses of Recursion in Imperative Languages
Is there a problem that has only a recursive solution, that is, a problem that has a recursive solution, but an iterative solution has yet to be found, or better yet, has proven to be non-existing (obviously, this is not a tail-recursion)?
replace function calls with pushing arguments onto a stack, and returns with popping off the stack, and you've eliminated recursion.
Edit: in response to "using a stack does not decrease space costs"
If a recursive algorithm can run in constant space, it can be written in a tail-recursive manner. if it is written in tail-recursive format, then any decent compiler can collapse the stack. However, this means the "convert function calls to explicit stack-pushes" method also takes constant space as well. As an example, lets take factorial.
factorial:
def fact_rec(n):
' Textbook Factorial function '
if n < 2: return 1
else: return n * f(n-1)
def f(n, product=1):
' Tail-recursive factorial function '
if n < 2: return product
else: return f(n-1, product*n)
def f(n):
' explicit stack -- otherwise same as tail-recursive function '
stack, product = [n], 1
while len(stack):
n = stack.pop()
if n < 2: pass
else:
stack.append(n-1)
product *= n
return product
because the stack.pop() follows the stack.append() in the loop, the stack never has more than one item in it, and so it fulfills the constant-space requirement. if you imagine using a temp variable instead of a 1-length stack, it becomes your standard iterative-factorial algorithm.
of course, there are recursive functions that can't be written in tail-recursive format. You can still convert to iterative format with some kind of stack, but I'd be surprised if there were any guarantees on space-complexity.
In Response to the Ackermann function answer, this is a pretty straightforward convert-the-call-stack-into-a-real-stack problem. This also shows one benefit of the iterative version.
on my platform (Python 3.1rc2/Vista32) the iterative version calculates ack(3,7) = 1021 fine, while the recursive version stackoverflows. NB: it didn't stackoverflow on python 2.6.2/Vista64 on a different machine, so it seems to be rather platform-dependant,
(Community wiki because this is really a comment to another answer [if only comments supported code formatting .... ])
def ack(m,n):
s = [m]
while len(s):
m = s.pop()
if m == 0:
n += 1
elif n == 0:
s.append(m-1)
n = 1
else:
s.append(m-1)
s.append(m)
n -= 1
return n
The Ackermann function cannot be expressed without recursion
edit: As noted in another answer, this is incorrect.
You can define a Turing Machine without recursion (right?) So recursion isn't required for a language to be Turing-complete.
In programming, recursion is really a special case of iteration - one where you use the call stack as a special means of storing state. You can rewrite any recursive method to be an iterative one. It may be more complicated or less elegant, but it's equivalent.
In mathematics, there are certain problems that require recursive techniques to arrive at an answer - some examples are finding roots (Newton's Method), computing primes, graph optimization, etc. However, even here, there's just a question of how you differentiate between the terms "iteration" and "recursion".
EDIT: As others have pointed out, there exist many functions whose definition is recursive - ex. the Ackermann function. However, this does not mean that they cannot be computed using iterative constructs - so long as you have a turing complete operation set and unlimited memory.
All non np-complete problems can be solved with just sequence, decision, and iteration. Recursion should not be required, though it usually greatly simplifies the problem.
It comes down to how many lines of code is it going to take to solve the problem...
List all the files on your C:\ using recursion and then without. Sure you can do it both ways - but one way is going to be a lot simpler to understand and debug.
No. Recursion is nothing more than a stack and you can achieve the same results by implementing a stack explicitly.
That may not be an especially satisfying answer, but you'd have to ask a much more specific question to get a better answer. For example, theory dictates that in the levels of computing there is quite a difference in the range of problems that can be solved if you have a while loop vs. only having (traditional) for loops.
I put "traditional" in there because they really mean loops that iterate a certain number of times whereas C style for (...;...;...) loops are while loops in disguise.