How can I create a power function with negative exponent in Clojure? - clojure

I've seen many ways to develop a power function in Clojure (recursion, using reduce, loop, etc), but none of them accepts negative exponents...
Can I do this without depending on Java's Math/pow?

Here is a hint of how you could use the regular algorithms:

Related

cudd C++ interface. A suggestion for reading the string-formatted Boolean expressions into cudd?

A follow up to my earlier post, CUDD C++ Interface for converting Booleans to BDDs and resulting set of minterms (to cutsets).
In the tulip-dd BDD lib., which runs on Python, one can define and read Boolean expressions as strings. That makes the whole I/O process very convenient .
Now, we just saw in the prior post that using the cudd C++ interface we can define a Boolean expression conveniently using a compact math notation such as x1*x2 + x3*x4and how to produce the sum of minterms from that expression. But does cudd also allow us to use strings for the Boolean expressions? I suspect not, and if not, I would have to find a way to convert the string equivalent of the sum product above to the equivalent Boolean: "x1*x2+x3*x4"to x1*x2+x3*x4.

Using QScriptEngine to compute calculations

I'm creating a diagram modeling tool that connects Items to Tasks. Items have Properties (simple name/value relationships) and Tasks have Formulas. I intend to produce a UI for the users to write in a QLineEdit a formula using C++ syntax ( ie, (property1 * property2)/property3), and then output the result. Of course, the formula would have to be somehow parsed and computed to output the result.
My concern with this is if using QScriptEngine is appropriate for this. I've seen that it can be used to perform calculations using evaluate(). Besides the 4 "regular" operations ( +, -, * and /), I only anticipate that probably sqrt() and pow() might be required - but apparently, Math is also usable inside the evaluation string.
Also, I need to store and recover these formulas, so I was considering handling them as QStrings for that purpose, as I will need to write/read them to/from files.
Do you think this is a good approach? What would you suggest as a good read for this type of objectives?
Yes, this approach is good. I've used it for a similar task. Note that QScriptEngine uses JavaScript syntax, not C++ syntax. But JavaScript syntax is powerful and fulfills usual needs of user-defined formulas. It supports regular operators, math functions, brackets, local variables, etc.
You can store a formula in QString. If you need to execute the same formula multiple times, you should use QScriptProgram to compile a formula before executing.

Writing INTEGRATOR similar to http://integrals.wolfram.com/index.jsp using parsing in java

Hi as part of my project I have been working on evaluation of arithmetic expression using reg-ex in java.
expressions are like this : 2+3/4(5+7)
first I will modify it to this : 2+3/4*(5+7)
and convert it to postfix
postfix: 23457+*/+
The procedure I have adopted is parsing all of the tokens (i.e. Integers,Operators,Open Paren,Close Paren) using Reg-Ex and then sorting by the i-th position of their occurrence. After that I converted that array of token into post-fix expression and then solved that expression, Until this point every thing is working fine.
Now I would like to extend it to solving differentiation,integration or solving quadratic equation.
foe ex: differentiate or integrate expression x^2+2*x+2
similar to http://integrals.wolfram.com/index.jsp
Is it possible? because right now I dont have any clue how to proceed with that?
Most calculators I am aware of - calculating equations/differentions and integrals using numerical analysis. This allows one to find a close solution to the exact (analytical one) solution, sometimes even for unsolveable equations (This is how we got the standard normal table, for the unsolveable normal density function)
For example, solving integrals - gaussian quardature is very common and efficeint way.
For solving equations - regula-falsi method is a simple and intuitive one
I think that most integral computation engines use the numerical approach just as amit said, however there's a way to compute it symbolically, but it's heuristic more than algorithmic, it's done by pattern matching. I think that Mathematica follows this approach.

How to extend numerical protocols in Clojure

I'm trying to use protocols to create an engineering number type (a "knumber"), so I can say (+ "1k" "2Meg") and get something like "2.001Meg". I should be able to get the floating point value from the knumber like so (:val my-knumber), but normally the printer should display the string, which is also accessible like so (:string my-knumber). This number will support all the usual p, n, u, m, k, Meg, G suffixes, and convert as required among them, such as (/ "1Meg" "1G") -> "1m"). I want to be able to pass this to any function which expects a number.
Anyway, Can someone suggest a strategy for this? I think I need to use protocols. I currently have a (defrecord knumber [val string]) but I'm not sure what's next.
What protocols do clojure numbers satsify? I'm thinking I need to extend some existing protocols/interfaces for this.
Thanks
I think your strategy should probably be as follows:
Define the record KNumber as something like (defrecord knumber [value unit-map])
Make unit-map a map of units to integer exponents (you are going to want units like m/s^2 if these are engineering numbers, right?). It might look something like {"m" 1 "s" -2},
Have KNumber implement java.lang.Number so that you can use it with other mathematical functions that already exist in Clojure. You'll need to implement doubleValue, longValue etc.
Define a protocol NumberWithUnits that you can extend to both KNumbers and normal clojure numbers. At a minimum it should have methods (numeric-value [number]) and (get-units [number])
Then define your mathematical functions +, *, - etc. in your own namespace that operate on anything that implements the NumberWithUnits protocol and return a KNumber.
Regarding different unit scales (e.g. "m" vs. "km") I would suggest standardising on a single scale for internal representation for each unit type (e.g. "m" for distances) but providing options for conversion to other unit scales for input/output purposes.
The frinj library is a Clojure library for calculations with units. Looking into the source will probably give you some nice ideas.

calculating user defined formulas (with c++)

We would like to have user defined formulas in our c++ program.
e.g. The value v = x + ( y - (z - 2)) / 2. Later in the program the user would define x,y and z -> the program should return the result of the calculation. Somewhen later the formula may get changed, so the next time the program should parse the formula and add the new values. Any ideas / hints how to do something like this ? So far I just came to the solution to write a parser to calculate these formulas - maybe any ideas about that ?
If it will be used frequently and if it will be extended in the future, I would almost recommend adding either Python or Lua into your code. Lua is a very lightweight scripting language which you can hook into and provide new functions, operators etc. If you want to do more robust and complicated things, use Python instead.
You can represent your formula as a tree of operations and sub-expressions. You may want to define types or constants for Operation types and Variables.
You can then easily enough write a method that recurses through the tree, applying the appropriate operations to whatever values you pass in.
Building your own parser for this should be a straight-forward operation:
) convert the equation from infix to postfix notation (a typical compsci assignment) (I'd use a stack)
) wait to get the values you want
) pop the stack of infix items, dropping the value for the variable in where needed
) display results
Using Spirit (for example) to parse (and the 'semantic actions' it provides to construct an expression tree that you can then manipulate, e.g., evaluate) seems like quite a simple solution. You can find a grammar for arithmetic expressions there for example, if needed... (it's quite simple to come up with your own).
Note: Spirit is very simple to learn, and quite adapted for such tasks.
There's generally two ways of doing it, with three possible implementations:
as you've touched on yourself, a library to evaluate formulas
compiling the formula into code
The second option here is usually done either by compiling something that can be loaded in as a kind of plugin, or it can be compiled into a separate program that is then invoked and produces the necessary output.
For C++ I would guess that a library for evaluation would probably exist somewhere so that's where I would start.
If you want to write your own, search for "formal automata" and/or "finite state machine grammar"
In general what you will do is parse the string, pushing characters on a stack as you go. Then start popping the characters off and perform tasks based on what is popped. It's easier to code if you force equations to reverse-polish notation.
To make your life easier, I think getting this kind of input is best done through a GUI where users are restricted in what they can type in.
If you plan on doing it from the command line (that is the impression I get from your post), then you should probably define a strict set of allowable inputs (e.g. only single letter variables, no whitespace, and only certain mathematical symbols: ()+-*/ etc.).
Then, you will need to:
Read in the input char array
Parse it in order to build up a list of variables and actions
Carry out those actions - in BOMDAS order
With ANTLR you can create a parser/compiler that will interpret the user input, then execute the calculations using the Visitor pattern. A good example is here, but it is in C#. You should be able to adapt it quickly to your needs and remain using C++ as your development platform.