as400 CL script arithmetic gives 0 - math

I'm trying to calculate the remainder of a division with the algorithm:
remainder = dividend - (dividend / divisor) * divisor
All calculated in integers.
Example:
Get the remainder of 15 / 6.
1. (15 / 6) = 2
2. (2) * 6 = 12
3. 15 - 12 = 3
The remainder of 15/6 is indeed 3.
My problem is using this algorithm in my CL script simply returns 0 all the time. Why is that?
pgm
dcl var(&dividend) type(*int) value(15)
dcl var(&divisor) type(*int) value(6)
dcl var(&remainder) type(*int)
dcl var(&msg) type(*char)
/* Calculate remainder. [ed: 29Sep2016] "* &remainder" is now: "* &divisor" */
chgvar var(&remainder) value(&dividend - (&dividend / &divisor) * &divisor)
/* Prior to 29-Sep-2016 redaction, the above was coded as the incorrect expression: +
chgvar var(&remainder) value(&dividend - (&dividend / &divisor) * &remainder) +
and remains, commented-out, to preserve relevance of user-comments about the OP */
/* Cast remainder and display. */
chgvar var(&msg) value(&remainder)
sndpgmmsg msg(&msg)
endpgm
Compiled with:
crtclpgm pgm(test) srcfile(test) srcmbr(test)
Run:
call test
Output:
0

This is quite interesting system behaviour. It would seem that the engine doesn't apply the integer trunking on the values in the brackets before multiplying it. So in other words the following is happening:
&dividend - (&dividend / &divisor) * &divisor
= 15 - (15 / 6) * 6
= 15 - 2.5 * 6
= 15 - 15
= 0
To fix it I did the following:
chgvar var(&remainder) value(&dividend / &divisor)
chgvar var(&remainder) value(&dividend - &remainder * &divisor)

The described result is a side effect of the / that was coded as the division operator. The / operator is not an integer division operator in the CL; some languages might offer the // as an additional division operator for that effect, or perhaps as a scalar function such as a DIV; though when a language offers such additional arithmetic features, they are likely also to offer a related scalar such as MOD or REM to directly obtain a remainder.
The IRP listing revealed the CL operated as if explicitly coded as having an intermediate value with non-zero scale; effectively TYPE(*DEC) LEN(24 9), but the CL only allow 15 digits of precision, so I use TYPE(*DEC) LEN(15 5) in this example of a program that mimics the creation of the intermediate result for the division before performing the rest of the expression:
pgm
dcl var(&dividend) type(*int) value(15)
dcl var(&divisor) type(*int) value(6)
dcl var(&remainder) type(*int)
dcl var(&intermedP) type(*dec) len(15 5)
/* Calculate remainder. *two-step process -- mimics IRP listing; yields 0 */
chgvar var(&intermedP) value(&dividend / &divisor) /* P15,5 intermed result */
chgvar var(&remainder) value(&dividend - &intermedP * &divisor )
Because the proper result requires that the (&dividend / &divisor) [as part of the expression &dividend - (&dividend / &divisor) * &divisor] must yield an integer result, that means the intermediate result for that division operation must be forced to either the *INT type or to another numeric type with zero-scale.
And as the already-accepted answer shows, the following revision to use an integer for the intermediate result resolves the issue:
pgm
dcl var(&dividend) type(*int) value(15)
dcl var(&divisor) type(*int) value(6)
dcl var(&remainder) type(*int)
dcl var(&intermedI) type(*int)
/* Calculate remainder. *two-step process; per change, correctly yields 3 */
chgvar var(&intermedI) value(&dividend / &divisor) /* *INT intermed result */
chgvar var(&remainder) value(&dividend - &intermedI * &divisor )
Unlike what I alluded in a 24Sep comment to the OP, there is no ability to code the following expression to achieve the desired result in just one CHGVAR statement; the first expression fails syntax checking with msg CPD0058 "Built-in function %INT allows 1 arguments." and the second fails with msg CPD0181 "Argument for built-in function %INT not valid.". And I would expect the same effect [but I did not verify] from coding the %DEC builtin [with specification of a zero-scale; i.e. zero specified for the decimal-places argument]:
( &dividend - %int(&dividend / &divisor) * &divisor )
( &dividend - %int((&dividend / &divisor)) * &divisor )

Related

Understanding recursion in Elixir

Forgive me if this is basic but I'm new to Elixir and trying to understand the language.
Say I have this code
defmodule Test do
def mult([]), do: 1
def mult([head | tail]) do
IO.puts "head is: #{head}"
IO.inspect tail
head*mult(tail)
end
end
when I run with this: Test.mult([1,5,10])
I get the following output
head is: 1
[5, 10]
head is: 5
'\n'
head is: 10
[]
50
But I'm struggling to understand what's going on because if I separately try to do this:
[h | t] = [1,5,10]
h * t
obviously I get an error, can someone explain what I'm missing?
Your function breaks down as:
mult([1 | [5, 10]])
1 * mult([5 | [10]])
1 * 5 * mult([10 | []])
1 * 5 * 10 * mult([])
1 * 5 * 10 * 1
50
The '\n' is actually [10] and is due to this: Elixir lists interpreted as char lists.
IO.inspect('\n', charlists: :as_lists)
[10]
Consider the arguments being passed to mult on each invocation.
When you do Test.mult([1,5,10]) first it checks the first function clause; that is can [1,5,10] be made to match []. Elixir will try to make the two expressions match if it can. In this case it cannot so then it tries the next function clause; can [1,5,10] be made to match [head|tail]? Yes it can so it assigns the first element (1) to head and the remaining elements [5,10] to tail. Then it recursively calls the function again but this time with the list [5,10]
Again it tries to match [5,10] to []; again this cannot be made to match so it drops down to [head|tail]. This time head is 5 and tail is 10. So again the function is called recursively with [10]
Again, can [10] be made to match []? No. So again it hits [head|tail] and assigns head = 10 and tail = [] (remember there's always an implied empty list at the end of every list).
Last go round; now [] definitely matches [] so it returns 1. Then the prior head * mult(tail) is evaluated (1 * 10) and that result is returned to the prior call on the stack. Evaluated again head (5) * mult(tail) (10) = 50. Final unwind of the stack head (1) * mult(tail) (50) = 50. Hence the overall value of the function is 50.
Remember that Elixir cannot totally evaluate any function call until it evaluates all subsequent function calls. So it hangs on to the intermediate values in order to compute the final value of the function.
Now consider your second code fragment in terms of pattern matching. [h|t] = [1,5,10] will assign h = 1 and t = [5,10]. h*t means 1 * [5,10]. Since those are fundamentally different types there's no inbuilt definition for multiplication in this case.

Logic of computing a^b, and is power a keyword?

I found the following code that is meant to compute a^b (Cracking the Coding Interview, Ch. VI Big O).
What's the logic of return a * power(a, b - 1); ? Is it recursion
of some sort?
Is power a keyword here or just pseudocode?
int power(int a, int b)
{ if (b < 0) {
return a; // error
} else if (b == 0) {
return 1;
} else {
return a * power(a, b - 1);
}
}
Power is just the name of the function.
Ya this is RECURSION as we are representing a given problem in terms of smaller problem of similar type.
let a=2 and b=4 =calculate= power(2,4) -- large problem (original one)
Now we will represent this in terms of smaller one
i.e 2*power(2,4-1) -- smaller problem of same type power(2,3)
i.e a*power(a,b-1)
If's in the start are for controlling the base cases i.e when b goes below 1
This is a recursive function. That is, the function is defined in terms of itself, with a base case that prevents the recursion from running indefinitely.
power is the name of the function.
For example, 4^3 is equal to 4 * 4^2. That is, 4 raised to the third power can be calculated by multiplying 4 and 4 raised to the second power. And 4^2 can be calculated as 4 * 4^1, which can be simplified to 4 * 4, since the base case of the recursion specifies that 4^1 = 4. Combining this together, 4^3 = 4 * 4^2 = 4 * 4 * 4^1 = 4 * 4 * 4 = 64.
power here is just the name of the function that is defined and NOT a keyword.
Now, let consider that you want to find 2^10. You can write the same thing as 2*(2^9), as 2*2*(2^8), as 2*2*2*(2^7) and so on till 2*2*2*2*2*2*2*2*2*(2^1).
This is what a * power(a, b - 1) is doing in a recursive manner.
Here is a dry run of the code for finding 2^4:
The initial call to the function will be power(2,4), the complete stack trace is shown below
power(2,4) ---> returns a*power(2,3), i.e, 2*4=16
|
power(2,3) ---> returns a*power(2,2), i.e, 2*3=8
|
power(2,2) ---> returns a*power(2,1), i.e, 2*2=4
|
power(2,1) ---> returns a*power(2,0), i.e, 2*1=2
|
power(2,0) ---> returns 1 as b == 0

Using Complex Numbers in ODE Problem returns Inexact Error

I am trying to implement to Swing equation for a n-Machine system using Julia.
When i run the following code I get this Error Message:
LoadError: InexactError: Float64(0.0 + 1.0im)
in expression starting at /home/Documents/first_try.jl:61
Swing_Equation(::Array{Float64,1}, ::Array{Float64,1}, ::Array{Float64,1}, ::Float64) at complex.jl:37
ODEFunction at diffeqfunction.jl:219 [inlined]
initialize!
The problem is occuring since I am using du[3] = (u[3] * u[2]) * im which can not be a Float64 type. The code is working fine when I remove the im - but then it is not the model I want to implement anymore.
What way is there to work around my problem?
using Plots
using DifferentialEquations
inspectdr()
# Constants
P_m0 = 0.3 # constant Mechanical Power
P_emax = 1
H = 1.01 # Inertia constant of the system
θ_0 = asin(P_m0 / P_emax) # angle of the system
ω_0 = 1.0 # initial angular velocity
M = 2 * H / ω_0
D = 0.9 # Damping constant
u02 = [θ_0;ω_0] # Initial Conditions
tspan = (0.0,100.0) # Time span to solve for
p = [M;P_m0;D]
i = 3
function Swing_Equation(du,u,t,p) # u[1] = angle θ
du[1] = u[2] # u[2] = angular velocity ω
P_e = real(u[3] * conj(i))
du[2] = (1 / M) * ( P_m0 - P_e - D * u[2]) # du[2] = angular acceleration
du[3] = (u[3] * u[2]) * im
end
# solving the differential equations
prob2 = ODEProblem(Swing_Equation,u0,tspan,p)
print(prob2)
sol2 = solve(prob2)
# Visualizing the solutoins
plot(sol2; vars = 1, label = "Θ_kura", line = ("red"))
plot!(sol2; vars = 2, label = "ω_kura", line = ("blue"))
gui()
plot(sol2,vars = (1,2),label="Kurmamoto" ,line = ("purple"))
xlabel!("Θ")
ylabel!("ω")
gui()
The problem is most likely in your input.
prob2 = ODEProblem(Swing_Equation,u0,tspan,p)
I am guessing that in this part you are providing an array of Float64 for u0? Your Swing_Equation then receives u as an Array{Float64} type. I suspect that also means du is the same.
This causes the expression
du[3] = (u[3] * u[2]) * im
to fail because you are trying to assign a Complex{Float64} number to du[3] which is of type Float64. Julia will then try to perform a
convert(Float64, (u[3] * u[2]) * im)
Which will cause the inexact error, because you cannot convert a complex number to a floating point number.
The Solution is to make sure du and u are complex numbers so you avoid this conversion. A quick and dirty way to solve that would be to write:
prob2 = ODEProblem(Swing_Equation, collect(Complex{Float64}, u0),tspan,p)
This will collect all elements in u0 and create a new array where every element is a Complex{Float64}. However this assumes a 1D array. I don't know your case. I don't work with ODE solvers myself.
General Advice to avoid this kind of problem
Add some more type assertions to in your code to make sure you get the kind of inputs you expect. This will help catch these kinds of problem and make you more easily see what is going on.
function Swing_Equation(du::AbstractArray{T}, u::AbstractArray{T}, t,p) where T<:Complex # u[1] = angle θ
du[1] = u[2] :: Complex{Float64}
P_e = real(u[3] * conj(i))
du[2] = (1 / M) * ( P_m0 - P_e - D * u[2]) # du[2] = angular acceleration
du[3] = (u[3] * u[2]) * im
end
Keep in mind Julia is a bit more demanding when it comes to matching up types than other dynamic languages. That is what gives it the performance.
Why is Julia different from Python in this case?
Julia does not upgrade types like Python to whatever fits. Arrays are typed. They cannot contain anything like in Python and other dynamic languages. If you e.g. made an array where each element is an integer, then you cannot assign float values to each element without doing an explicit conversion to floating point first. Otherwise Julia has to warn you that you are getting an inexact error by throwing an exception.
In Python this is not a problem because every element in an array can be a different type. If you want every element in a Julia array to be a different number type then you must create the array as a Array{Number} type but these are very inefficient.
Hope that helps!

Ada: Access first element in Real_Matrix with one row and one column

PROBLEM STATEMENT
I have a Real_Matrix with one row and one column. I would like to evaluate the value of the single element on row one, column one. I'm getting an error when I try to access the Matrix using the: Matrix(I, J) syntax. See below:
CODE
with Ada.Numerics.Real_Arrays; use Ada.Numerics.Real_Arrays;
with Ada.Text_IO; use Ada.Text_IO;
procedure Matrix is
------------------------------------
-- Real_Matrix Division Operation --
------------------------------------
function "/" (Left : Real_Matrix;
Right : Real_Matrix) return Real_Matrix
is
begin
return Left * Inverse(Right);
end "/";
α : Real_Matrix := ( ( Integer'First => 1.0 ),
( Integer'First => 2.0 ) );
β : Real_Matrix := ( ( Integer'First => 3.0 ),
( Integer'First => 4.0 ) );
begin
-- This operation returns an matrix with one row and one column --
Put_Line(Float'Image(((Transpose(α) * α) / (Transpose(β) * β))(Integer'First, Integer'First))); -- Error: Missing "," --
end Matrix;
I think you need a real language lawyer to tell you whether this is a compiler failure or proper behaviour, but your code will compile if you force the compiler to recognise that the / operation produces a Real_Matrix:
Put_Line
(Float'Image
(Real_Matrix'((Transpose(α) * α) / (Transpose(β) * β))
(Integer'First, Integer'First)));
When I tried this, I got a Constraint_Error; so I tried #BrianDrummond’s suggestion,
γ : constant Real_Matrix := (Transpose(α) * α) / (Transpose(β) * β);
and it turns out that γ’First (1) is -2147483648, whereas γ’First (2) is 1 (this is GNAT GPL 2016 on macOS Sierra).
Further investigation: I’m pretty sure this is a bug in GNAT’s Inverse.
ARM G.3.1(72) says
This function returns a matrix B such that A * B is (nearly) equal to the unit matrix. The index ranges of the result are A'Range(2) and A'Range(1). Constraint_Error is raised if A'Length(1) is not equal to A'Length(2). Constraint_Error is raised if the matrix A is ill-conditioned.
and GNAT’s implementation is
function Inverse (A : Real_Matrix) return Real_Matrix is
(Solve (A, Unit_Matrix (Length (A))));
where Solve (same reference, (70)) says
This function returns a matrix Y such that X is (nearly) equal to A * Y. This is the standard mathematical operation for solving several sets of linear equations. The index ranges of the result are A'Range(2) and X'Range(2). Constraint_Error is raised if A'Length(1), A'Length(2), and X'Length(1) are not equal. Constraint_Error is raised if the matrix A is ill-conditioned.
and Unit_Matrix (same reference, (79)) is
function Unit_Matrix (Order : Positive;
First_1, First_2 : Integer := 1) return Real_Matrix;
Notice the default values for First_1, First_2!

Redefine the infix operators

I am learning Jason Hickey's Introduction to Objective Caml.
Just have a question about Redefine the infix operators.
So in the book, there is such a paragraph:
# let (+) = ( * )
and (-) = (+)
and ( * ) = (/)
and (/) = (-);;
val + : int > int > int = <fun>
val - : int > int > int = <fun>
val * : int > int > int = <fun>
val / : int > int > int = <fun>
# 5 + 4 / 1;;
-: **int = 15**
First, how does these redefinition work?
To me, it seems the functions are running in a kind of indefinite loop, because all the operations seem redefined and connected.
for example, if I do 1+2, then it will be 1 * 2 and since ( * ) = (/), it will be then 1 / 2 and since (/) = (-), then it will be 1-2, so on so forth. Am I right?
Second, will the result of 5 + 4 / 1 be 15, even if the functions are executed only one step further in the redefinition?
So assume the redefinition will be execute one step further, i.e., 1 + 2 will only be 1 * 2 and no more transform, so 5 + 4 / 1 should be 5 * 4 -1, right? then the answer is 19. Am I correct?
To me, it seems the functions are running in a kind of indefinite
loop, because all the operations seem redefined and connected.
Not really, it's just a simultaneous re-definition of infix operators (with the and keyword). What you see is not a recursive definition. In OCaml, recursive definitions are made with let rec (as you may already know).
For the second part of the question, I think it's a matter of operator precedence. Note that in the original expression 5 + 4 / 1 is actually 5 + (4/1) following the usual precedence rules for arithmetic operators. So, I think the conversion simply preserves this binding (sort of). And you get 5 * (4 - 1) = 15.
The key observation (IMHO) is that (+) is being defined by the preexisting definition of ( * ), not by the one that appears a few lines later. Similarly, ( * ) is being defined by the preexisting definition of (/). As Asiri says, this is because of the use of let rather than let rec.
It's also true that in OCaml, precedence and associativity are inherent in the operators and can't be changed by definitions. Precedence and associativity are determined by the first character of the operator.
If you look at the table of operator precedences and associativities in Section 6.7 of the OCaml Manual, you'll see that all the entries are defined for "operators beginning with character X".

Resources