Reading back through some of my old Python code to refresh myself on the "Yield" keyword, I realized that I have not seen a similar idea in Julia. Does an analog version of Yield exist? (Note that Julia's Base library comes with a yield function but that is for tasks and does not act like the yield keyword does in Python).
There are no built-ins for yield (unfortunately, if you ask me). However, since Julia has a very advanced macro system, and the theory as well as multiple possible implementations of coroutines/generators are quite well studied, there are a couple of implementations in third-party packages.
One of them is FGenerators.jl, previously GeneratorsX.jl, which works mostly in the transducers ecosystem.
Another is ResumableFunctions.jl.
You can construct generators that yield values when iterated upon:
f(x) = x*x
g = (f(i) for i=1:5) #generator that yields values
for x in g
println(x)
end
Related
I am interested in Julia and would like to understand a couple of things before I dive into it. I would like to have a look at a working code which calculates this expression.
In that expression everything is a constant but for the Bessel functions, of course. The number n is an integer and "e" is an eccentricity (ranging from 0. to, say, 0.999).
For a given value of n I would like to derive hc,n. E.g. if n=2, then hc,2.
No, I am not tricking you into coding for me.
I am used to working with shell scripts, bc, and plot with gnuplot. I would like to have something more flexible than all of this and this one would be a good example to start looking at julia. Thanks!
For the best tutorial on doing equations/mathematics in Julia have a look at https://github.com/mossr/BeautifulAlgorithms.jl
This will give you an excellent overview along with the initial feelling of the language.
I am using Julia v0.3.5, which comes with WinPython 3.4.2.5 build 4. I am new to Julia. I am testing how fast Julia is compared to using SciPy's BLAS wrapper for ddot(), which has the following arguments: x,y,n,offx,incx,offy,incy. Julia's OpenBLAS library does not have the offset arguments, so I am trying to figure out how to emulate them while maximizing speed. I am passing 100MB subarrays of a 1GB array (vector) multiple times, so I don't want Julia to create a copy of each subarray, which would reduce the speed. Python's SciPy function is taking a couple of hours to execute, so would like to optimize Julia's speed. I have been reading about how Julia 0.4 will offer array views that avoid the unnecessary copy, but I am unclear about how Julia 0.3.5 handles this.
So far, I learned using REPL that the BLAS dot() function conflicts with the method in linalg/matmul.jl. Therefore, I learned to access it this way:
import Base.LinAlg.BLAS
methods(Base.LinAlg.BLAS.dot)
From the method display, I see that I can pass pointers to x and y subarrays and thus avoid a copy. For example:
x = [1., 2., 3.]
y = [4., 5., 6.]
Base.LinAlg.BLAS.dot(2, pointer(x), 1, pointer(y), 1)
However, when I add an integer offset to a pointer (to access a subarray), REPL crashes.
How can I pass a pointer to a subarray or a subarray to Base.LinAlg.BLAS.dot without the slowdown of a copy of that subarray?
Anything else I missed?
It segfaults because pointer arithmatic doesn't work like you probably think it does (i.e. the C way). pointer(x)+1 is one byte after pointer(x), but you probably want pointer(x)+8, e.g.
Base.LinAlg.BLAS.dot(2, pointer(x)+1*sizeof(Float64), 1, pointer(y)+1*sizeof(Float64), 1)
or, more user friendly and recommended:
Base.LinAlg.dot(x,2:3,y,2:3)
which is defined here.
I'd say using pointers like that in Julia is really not recommended, but I imagine if you are doing this at all then it is a special circumstance.
For the cause of simplicity, Smallbasic has only global variables. It does not have locals or parameters.
Although this makes it simpler to teach or learn it, it also complicates some matters, like recursive functions. I had a hard time creating a simple recursive function in smallbasic and had to use a manual stack. This works but it makes it more complicated and contradicts the initial main goal of simplicity!
This is how i can write the factorial:
n = 5
ind = 1
fact()
TextWindow.WriteLine("fact(5)=" + f)
Sub fact
If n = 1 Then
f = 1
Else
ind = ind+1
keepn[ind] = n
n = n-1
fact()
f = f * keepn[ind]
ind = ind-1
EndIf
EndSub
Note: I wrote it just now and it could have errors.
You see the picture. I'm manually creating a stack and using it to simulate local variable and use it for recursion.
Is there an easy way to create this recursive function?
I think you do have to resort to global variables to write a recursive function in SmallBasic.
I'd agree that SmallBasic's lack of function arguments is quite limiting and often makes a supposedly simple programming language quite complex to use in practice.
SmallBasic's library however is great for beginners, making it significantly easier to put things on the screen than enterprise frameworks like WinForms or WPF. The library, SmallBasicLibrary.dll, can be easily loaded into other .Net languages including VB.Net, C# and F#. Simply create a console application and add a reference to the library and then use import/using/open against the Library namespace.
While teaching my kids programming I started with SmallBasic, they loved the Turtle functionality, but then quickly switched to F# which has first-class support for functions and far less ceremony when compared to VB.Net or C#. Having to explain public static void Main to a 7yo before they could print "Hello World" just wasn't an attractive option to me.
As an experiment I've also created an alternative SmallBasic compiler implementation which you may find interesting as it includes support for function arguments, tuples and pattern matching.
I think it's worth noting that creating a recursive function in this way - i.e. with only global variables, using a stack - is very educational in its own right. This is closer to the way assembly works, so from that perspective having to do things this way could actually be considered a feature...
Is there a programming language where you don't have to define actors yourself - every function is just ran as a separate actor (which can mean a separate thread if there are free cores available) by default?
For example it means that if I write something as simple as
v = fA(x) + fB(y)
then fA and fB could be calculated simultaneously before the sum of their results was assigned to v.
I don't think there is anything this extreme, since the context switching and comunication overhead would be too big.
The closest I can think of to what you are asking is data-parallel programing, where the program is mostly written in the same style as a sequential version but parts of it are ran in parallel where possible.
Examples are loop vectorization in Fortran and "par" magic in Haskell.
Haskell's par combinator lets you evaluate expressions concurrently (which can mean in separate threads if there are free cores available). All you have to do is:
x `par` y
Which will evaluate x and y concurrently, and return the value of y. Note that x and y can be programs of arbitrary complexity.
Joule is a pure asynchronous message passing language:
http://en.wikipedia.org/wiki/Joule_%28programming_language%29
http://www.erights.org/history/joule/MANUAL.BK5.pdf
ActorScript is a pure Actor message-passing language, but appears to only exist as a specification:
http://arxiv.org/abs/1008.2748
What is the smartest way to design a math parser? What I mean is a function that takes a math string (like: "2 + 3 / 2 + (2 * 5)") and returns the calculated value? I did write one in VB6 ages ago but it ended up being way to bloated and not very portable (or smart for that matter...). General ideas, psuedo code or real code is appreciated.
A pretty good approach would involve two steps. The first step involves converting the expression from infix to postfix (e.g. via Dijkstra's shunting yard) notation. Once that's done, it's pretty trivial to write a postfix evaluator.
I wrote a few blog posts about designing a math parser. There is a general introduction, basic knowledge about grammars, sample implementation written in Ruby and a test suite. Perhaps you will find these materials useful.
You have a couple of approaches. You could generate dynamic code and execute it in order to get the answer without needing to write much code. Just perform a search on runtime generated code in .NET and there are plenty of examples around.
Alternatively you could create an actual parser and generate a little parse tree that is then used to evaluate the expression. Again this is pretty simple for basic expressions. Check out codeplex as I believe they have a math parser on there. Or just look up BNF which will include examples. Any website introducing compiler concepts will include this as a basic example.
Codeplex Expression Evaluator
If you have an "always on" application, just post the math string to google and parse the result. Simple way but not sure if that's what you need - but smart in some way i guess.
I know this is old, but I came across this trying to develop a calculator as part of a larger app and ran across some issues using the accepted answer. The links were IMMENSELY helpful in understanding and solving this problem and should not be discounted. I was writing an Android app in Java and for each item in the expression "string," I actually stored a String in an ArrayList as the user types on the keypad. For the infix-to-postfix conversion, I iterated through each String in the ArrayList, then evaluated the newly arranged postfix ArrayList of Strings. This was fantastic for a small number of operands/operators, but longer calculations were consistently off, especially as the expressions started evaluating to non-integers. In the provided link for Infix to Postfix conversion, it suggests popping the Stack if the scanned item is an operator and the topStack item has a higher precedence. I found that this is almost correct. Popping the topStack item if it's precedence is higher OR EQUAL to the scanned operator finally made my calculations come out correct. Hopefully this will help anyone working on this problem, and thanks to Justin Poliey (and fas?) for providing some invaluable links.
The related question Equation (expression) parser with precedence? has some good information on how to get started with this as well.
-Adam
Assuming your input is an infix expression in string format, you could convert it to postfix and, using a pair of stacks: an operator stack and an operand stack, work the solution from there. You can find general algorithm information at the Wikipedia link.
ANTLR is a very nice LL(*) parser generator. I recommend it highly.
Developers always want to have a clean approach, and try to implement the parsing logic from ground up, usually ending up with the Dijkstra Shunting-Yard Algorithm. Result is neat looking code, but possibly ridden with bugs. I have developed such an API, JMEP, that does all that, but it took me years to have stable code.
Even with all that work, you can see even from that project page that I am seriously considering to switch over to using JavaCC or ANTLR, even after all that work already done.
11 years into the future from when this question was asked: If you don't want to re-invent the wheel, there are many exotic math parsers out there.
There is one that I wrote years ago which supports arithmetic operations, equation solving, differential calculus, integral calculus, basic statistics, function/formula definition, graphing, etc.
Its called ParserNG and its free.
Evaluating an expression is as simple as:
MathExpression expr = new MathExpression("(34+32)-44/(8+9(3+2))-22");
System.out.println("result: " + expr.solve());
result: 43.16981132075472
Or using variables and calculating simple expressions:
MathExpression expr = new MathExpression("r=3;P=2*pi*r;");
System.out.println("result: " + expr.getValue("P"));
Or using functions:
MathExpression expr = new MathExpression("f(x)=39*sin(x^2)+x^3*cos(x);f(3)");
System.out.println("result: " + expr.solve());
result: -10.65717648378352
Or to evaluate the derivative at a given point(Note it does symbolic differentiation(not numerical) behind the scenes, so the accuracy is not limited by the errors of numerical approximations):
MathExpression expr = new MathExpression("f(x)=x^3*ln(x); diff(f,3,1)");
System.out.println("result: " + expr.solve());
result: 38.66253179403897
Which differentiates x^3 * ln(x) once at x=3.
The number of times you can differentiate is 1 for now.
or for Numerical Integration:
MathExpression expr = new MathExpression("f(x)=2*x; intg(f,1,3)");
System.out.println("result: " + expr.solve());
result: 7.999999999998261... approx: 8
This parser is decently fast and has lots of other functionality.
Work has been concluded on porting it to Swift via bindings to Objective C and we have used it in graphing applications amongst other iterative use-cases.
DISCLAIMER: ParserNG is authored by me.