Modulo using negative numbers - modulo

I am writing a program in assembly to calculate the modulus of a number. I do not need help with the the program, but I do need help understanding how modulo works with negative numbers. I have researched stackoverflow but I seem to be finding conflicting results.
Also, I would like to know how it works purely in mathematical terms, not as it relates to programming, just so I understand the basic concept. I did find this page semi-useful: Modulo operation with negative numbers However, the top two answers seem to be conflicting and now I have gotten myself even more confused with the difference between modulo vs remainders (based on the answers given on that page). Not to say that their answers are poor in any way, but at this point I seem to be having difficulty finding the forest through the trees.
Please help me answer these simple problems, and explain to to me in purely mathematical terms how you reached your answer. Also, I don't need to be explained the difference between modulo and remainder since I just seemed to become more confused when I looked at the webpage listed. Please explain it to me just in terms of modulus, and I can connect the dots from there ;)
Here are some examples:
-15 mod 2 = ?
15 mod -2 = ?
-4 mod 9 = ?
4 mod -9 = ?
-5 mod -9 = ?
Thank you in advance for your responses!

There is no clear convention for those cases.
Remember the formula for modulo is: n = am + b. Usually, it is required that the remainder b is within the interval [0..(m-1)]. This makes it very easy for all natural numbers.
For negative numbers, some conventions want the remainder to be in the interval [-(m-1)..0], some stick with above definition, and some take the solution where |b| is minimal.
Thus, you have to try the implementation the compiler or library developer chose.
Some programming languages have two operators to give you some freedom. Ada for example has rem and mod.
Behaviour:
In (n rem m) the remainder always has the sign of n, while in (n mod m), it takes on the sign of m.
The third convention, using the smaller remainder of the two, rarely is implemented.

Related

Z3: Complex numbers?

I have been searching on whether z3 supports complex numbers and have found the following: https://leodemoura.github.io/blog/2013/01/26/complex.html
The author states that (1) Complex numbers are not yet implemented in Z3 as a built-in (this was written in 2013), and (2) that Complex numbers can be encoded on top of the Real numbers provided by Z3.
The basic idea is to represent a Complex number as a pair of Real numbers. He defines the basic imaginary number with I=(0,1), that is: I means the real part equals 0 and the imaginary part equals 1.
He offers the encoding (I mean, we can test it on our machines), where we can solve the equation x^2+2=0. I received the following result:
sat
x = (-1.4142135623?)*I
The sat result does make sense, since this equation is solvable in the simulation of the theory of complex numbers (as a result of the theory of algebraically closed fields) we have just made. However, the root result does not make sense to me. I mean: what about (1.4142135623?)*I?
I would understand to receive the two roots, but, if only one received, I do not understand why I get the negated solution.
Maybe I misread something or I missed something.
Also, I would like to say if complex numbers have already been implemented built in Z3. I mean, with a standard:
x = Complex("x")
And with tactics of kind of a NCA (from nonlinear complex arithmetic).
I have not seen any reference to this theory in SMT-LIB either.
AFAIK there is no plan to add complex numbers to SMT-LIB. There's a Google group for SMT-LIB and it might make sense to send a post there to see if there is any interest there.
Note, that particular blog post says "find a root"; this is just satisfiability, i.e. it finds one solution, not all of them. (But you can ask for another one by adding an assertion that says x should be different from the first result.)

Performance issues with z3py using modulo and optimization

I'm experimenting with Z3 (using the python api) where I'm building up a scheduling model for a class assignment, where I have to use modulo quite often (because its periodic). Modulo seems already to slow down z3 by a lot, but if I try do some optimization on top (minimize a cost function which is a sum), then it takes quite some time for fairly small problems.
Without optimization it works okayish (few seconds for a smaller problem). So that being said, I have now 2 questions:
1) Is there any trick with the modulo function of how to use it? I already assign the modulo value to a function. Or is there any other way to express periodic/ring behavior?
2) I am not interested in finding THE best solution. A good one, will be good enough. Is there a way to set some bounds for the cost function. Like, if know the upper and lower bound of it? Any other tricks, where I could use domain knowledge to find solutions fast.
Furthermore, I thought that if I ll use timeout option solver.set("timeout" 10000), then the solver would time out with the best solution so far. That doesnt seem to be the case. It just times out.
Impossible to comment on the mod function without seeing some code. But as a rule of thumb, division is difficult. Are you using Int values, or bit-vectors? If you are using unbounded integers, you might want to try bit-vectors which might benefit from better internal heuristics. Or try Real values, and then do a proper reduction.
Regarding how to get the "best so far" optimal value, see this answer: Finding suboptimal solution (best solution so far) with Z3 command line tool and timeout
Instead of using the built-in modulo and division, you could introduce uninterpreted functions mymod and mydiv, for which you only provide the necessary axioms of division and modulo that your problem requires. If I remember correctly, Microsoft's Ironclad and/or Ironfleet team did that when they had modulo/division-related performance problems (using the pipeline Dafny -> Boogie -> Z3).

CAS Mode in Nspire Lua?

I have another question here: Inspired Lua Program is Different on Computer and Calculator which answers this question. My attempt to mark as duplicate aged away.
I am writing a program for the Nspire CX CAS. I have a d2Editor mathbox that I would like to evaluate an expression I am giving it without using decimals. I would like it to simplify square roots and/or reduce fractions. How can this be accomplished?
I've spent around an hour looking through the wiki.
Thanks for any help you can offer.
Actually, no. I don't know if this is new but math.eval(expr) will evaluate expr as if you were running it from the tab calculator (Although still, if you have CAS disabled on your calculator, it will not be able to do use it)
math.eval('123+321=444') -> 'True'
Unless TI added new features recently, the answer is unfortunately that you will need to write it from scratch.
In a Lua program you do not have access to the representation that are used internally (say in a Notes workshop) to represent mathematical expressions.
You are handed, sigh, a string.
That means you will need to write your own parser for mathematical expressions in order to get a reasonable representation. Then you will need to write your own functions for manipulating and reducing expressions.
... no I am not kidding ...

Maxima gives crazy answer for integrate(exp(x^2))

I'm trying to learn how to use Maxima. Something goes wrong with integrate :
(%i) integrate(exp(x^3),x,1,2);
(%o) (gamma_incomplete(1/3,-8)-gamma_incomplete(1/3,-1))/3
(%i) float(%);
(%o) .3333333333333333 (- 715.7985328824436 %i - 413.26647564521807)
(%i) expand(%);
(%o) - 238.59951096081454 %i - 137.75549188173935
What do you think?
Comparing Maxima's result to Wolfram Alpha, looks like Maxima has assumed that -x/((-x^3)^(1/3)) = 1. After debugging this for a bit, I can't tell if that term was originally in the result and it got simplified away, or if it was never there. With that term in place, and using the principal branch for the cube root, I get 275.510983 + (epsilon)*%i which agrees with a numerical result, namely quad_qags(exp(x^3), x, 1, 2) => 275.510983.
For the record, this integral is handled as "Type 1a" in maxima/src/sin.lisp, in the function INTEGRATE-EXP-SPECIAL.
Mathematically, I don't think there's anything fundamentally wrong with a complex answer to an exponential integration. In general, If you integrate e^(x^n) you're going to run into strange functions like the incomplete gamma function etc, because the answer isn't expressible in conventional functions, so has no conventional real analytic solution.
However, I think that there's definitely some inaccuracy here. Mathematica gives a different answer, much closer to a real answer, and as I ask for more accuracy, the real part appears to tend to zero, as you would expect.
If you want to numerically integrate (and it sounds like you do), you'll could use a different function. integrate is for analytical integration, which is why it gave you a formula rather than a number. Look up quad_qags and its friends for some really clever numerical integration functions.

How to convert Latex formula to C/C++ code?

I need to convert a math formula written in the Latex style to the function of a C/C++ code.
For example:
y = sin(x)^2 would become something like
double y = sin(x) * sin(x);
or
double y = pow(sin(x), 2);
where x is a variable defined somewhere before.
I mean that it should convert the latex formula to the C/C++ syntax. So that if there is a function y = G(x, y)^F(x) it doesn't matter what is G(x,y) and F(x),
it is a problem of the programmer to define it. It will just generate
double y = pow(G(x, y), F(x));
When the formula is too complicated it will take some time to make include it in the C/C++ formula. Is there any way to do this conversion?
Emacs' built-in calculator calc-mode can do this (and much more). Your examples can be converted like this:
Put the formula in some emacs buffer
$ y = sin(x)^2 $
With the cursor in the formula, activate calc-embedded mode
M-x calc-embedded
Switch the display language to C:
M-x calc-c-language
There you are:
$ y == pow(sin(x), 2) $
Note that it interprets the '=' sign in latex as an equality, which results in '==' for C. The latex equivalent to Cs assignment operator '=' would be '\gets'.
More on this topic on Turong's blog
I know the question is too old, but I'll just add a reply anyway as a think it might help someone else later. The question popped up a lot for me in my searches.
I'm working on a tool that does something similar, in a public git repo
You'll have to put some artificial limitations on your latex input, that's out of question.
Currently the tool I wrote only supports mul, div, add, sub, sqrt, pow, frac and sum as those are the only set of operations I need to handle, and the imposed limitations can be a bit loose by providing a preprocessor (see preproc.l for an [maybe not-so-good] example) that would clean away the raw latex input.
A mathematical equation, such as the ones in LaTeX, and a C expression are not interchangeable. The former states a relation between two terms, the latter defines an entity that can be evaluated, unambiguously yielding one value. a = b in C means 'take the value in variable b and store it in variable a', wheres in Math, it means 'in the current context, a and b are equal'. The first describes a computation process, the second describes a static fact. Consequently, the Math equation can be reversed: a = b is equivalent to b = a, but doing the same to the C equation yields something quite different.
To make matters worse, LaTeX formulae only contain the information needed to render the equations; often, this is not enough to capture their meaning.
Of course some LaTeX formulae, like your example, can be converted into C computations, but many others cannot, so any automated way of doing so would only make limited sense.
I'm not sure there is a simple answer, because mathematical formulaes (in LaTeX documents) are actually ambiguous, so to automate their translation to some code requires automating their understanding.
And the MathML standard has, IIRC, two forms representing formulaes (one for displaying, another for computing) and there is some reason for that.

Resources