Explain the meaning of X02AJF(0.D0) - math

If I have this function in fortran
DOUBLE PRECISION FUNCTION X02AJF()
! RETURNS (1/2)*B**(1-P) IF ROUNDS IS .TRUE.
! RETURNS B**(1-P) OTHERWISE
DOUBLE PRECISION X02CON
DATA X02CON / 2.D-3 /
! .. Executable Statements ..
X02AJF = X02CON
RETURN
END
then what is the value of this variable
EPS = X02AJF(0.D0)
I can't know what mean this
X02AJF(0.D0)???
Is it mean EPS=0 ??

I can't know what mean this
X02AJF(0.D0)???
In strict accordance with the FORTRAN language, this is a wrong function call.
Is it mean EPS=0 ??
No. EPS == 2.D-3, but this is undefined behavior.
Informally, before the OPTIONAL attribute Fortran 90, many often violated the requirement of matching the number of arguments. For example, the System V ABI AMD64 defines a call to the FORTRAN function as similar to a call to the C function. Therefore, in this case, the result of X02AJF(0.D0) will be the same as X02AJF().

Related

porting python class to Julialang

I am seeing that Julia explicitly does NOT do classes... and I should instead embrace mutable structs.. am I going down the correct path here?? I diffed my trivial example against an official flux library but cannot gather how do I reference self like a python object.. is the cleanest way to simply pass the type as a parameter in the function??
Python
# Dense Layer
class Layer_Dense
def __init__(self, n_inputs, n_neurons):
self.weights = 0.01 * np.random.randn(n_inputs, n_neurons)
self.biases = np.zeros((1, n_neurons))
def forward(self, inputs):
pass
My JuliaLang version so far
mutable struct LayerDense
num_inputs::Int64
num_neurons::Int64
weights
biases
end
function forward(layer::LayerDense, inputs)
layer.weights = 0.01 * randn(layer.num_inputs, layer.num_neurons)
layer.biases = zeros((1, layer.num_neurons))
end
The flux libraries version of a dense layer... which looks very different to me.. and I do not know what they're doing or why.. like where is the forward pass call, is it here in flux just named after the layer Dense???
source : https://github.com/FluxML/Flux.jl/blob/b78a27b01c9629099adb059a98657b995760b617/src/layers/basic.jl#L71-L111
struct Dense{F, M<:AbstractMatrix, B}
weight::M
bias::B
σ::F
function Dense(W::M, bias = true, σ::F = identity) where {M<:AbstractMatrix, F}
b = create_bias(W, bias, size(W,1))
new{F,M,typeof(b)}(W, b, σ)
end
end
function Dense(in::Integer, out::Integer, σ = identity;
initW = nothing, initb = nothing,
init = glorot_uniform, bias=true)
W = if initW !== nothing
Base.depwarn("keyword initW is deprecated, please use init (which similarly accepts a funtion like randn)", :Dense)
initW(out, in)
else
init(out, in)
end
b = if bias === true && initb !== nothing
Base.depwarn("keyword initb is deprecated, please simply supply the bias vector, bias=initb(out)", :Dense)
initb(out)
else
bias
end
return Dense(W, b, σ)
end
This is an equivalent of your Python code in Julia:
mutable struct Layer_Dense
weights::Matrix{Float64}
biases::Matrix{Float64}
Layer_Dense(n_inputs::Integer, n_neurons::Integer) =
new(0.01 * randn(n_inputs, n_neurons),
zeros((1, n_neurons)))
end
forward(ld::Layer_Dense, inputs) = nothing
What is important here:
here I create an inner constructor only, as outer constructor is not needed; as opposed in the Flux.jl code you have linked the Dense type defines both inner and outer constructors
in python forward function does not do anything, so I copied it in Julia (your Julia code worked a bit differently); note that instead of self one should pass an instance of the object to the function as the first argument (and add ::Layer_Dense type signature so that Julia knows how to correctly dispatch it)
similarly in Python you store only weights and biases in the class, I have reflected this in the Julia code; note, however, that for performance reasons it is better to provide an explicit type of these two fields of Layer_Dense struct
like where is the forward pass call
In the code you have shared only constructors of Dense object are defined. However, in the lines below here and here the Dense type is defined to be a functor.
Functors are explained here (in general) and in here (more specifically for your use case)

Why is Ada not trapping this specified range check?

I am going through the learn.adacore.com tutorial and have hit upon a problem that I am unsure of.
Specifically I understand that Ada is designed to trap attempts to overflow a variable with a specified range definition.
In the case below, the first attempt to do this causes a compiler 'range check failure' which is expected. However the following line doesn't trap it and I am not sure why:
with Ada.Text_IO; use Ada.Text_IO;
procedure Custom_Floating_Types is
type T_Norm is new float range -1.0 .. 1.0;
D : T_Norm := 1.0;
begin
Put_Line("The value of D =" & T_Norm'Image(D));
-- D := D + 1.0; -- This causes a range check failure at run time = completely expected.
Put_Line("The value of D =" & T_Norm'Image(D + 1.0)); -- This doesn't?
end Custom_Floating_Types;
You have a couple of pretty good answers, but I'm going to add another because it's clear that you expect the expression D + 1.0 to raise an exception, and the answers you have don't explain why it doesn't.
A type declaration like
type T_Norm is new float range -1.0 .. 1.0;
is roughly equivalent to
type T_Norm'Base is new Float;
subtype T_Norm is T_Norm'Base range -1.0 .. 1.0;
The type (called the "base type") isn't given a name, though it can often be referenced with the 'Base attribute. The name that is given is to a subtype, called the "first-named subtype".
This distinction is important and is often not given enough attention. As explained by egilhh, T_Norm'Image is defined in terms of T_Norm'Base. This is also true of the arithmetic operators. For example, "+" is defined as
function "+" (Left : in T_Norm'Base; Right : in T_Norm'Base) return T_Norm'Base;
2.0 is clearly in the range of T_Norm'Base, so evaluating D + 1.0 doesn't violate any constraints, nor does passing it to T_Norm'Image. However, when you try to assign the resulting value to D, which has subtype T_Norm, a check is performed that the value is in the range of the subtype, and an exception is raised because the check fails.
This distinction is used in other places to make the language work reasonably. For example, a constrained array type
type A is array (1 .. 10) of C;
is roughly equivalent to
type A'Base is array (Integer range <>) of C;
subtype A is A'Base (1 .. 10);
If you do
V : A;
... V (2 .. 4)
you might expect problems because the slice doesn't have the bounds of A. But it works because the slice doesn't have subtype A but rather the anonymous subtype A'Base (2 ..4).
The definition of 'Image says:
For every scalar subtype S:
S'Image denotes a function with the following specification:
function S'Image(Arg : S'Base)
return String
As you can see, it takes a parameter of the base (unconstrained) type
T_Norm'Image(D + 1.0) neither assigns nor reads an out-of-range value. It asks for the 'Image attribute (string representation) of (D + 1.0), which is the same as asking for (1.0 + 1.0).
I can see two ways the confusion might arise. First, the name "attribute" could be misinterpreted to suggest that 'Image involves something intrinsic to D. It doesn't. The 'Image attribute is just a function, so D is just part of the expression that defines the value of the parameter (in your example = 2.0).
Second, the 'Image attribute comes from Float. Thus, any Float can be its parameter.
You can create a function that accepts only parameters of T_Norm'Range and make that function an attribute of T_Norm. See Ada Reference Manual 4.10.
Because you don't store a value greater than range in D.

How to set a default value for a SEXP parameter in Rcpp

I have a Rcpp function that has an optional argument which is the maturity of a financial instrument. This can be given as a string (e.g. "2y") or as a integer. If no value is given, the function needs to use a default integer. How can I set the default value for that argument?
I have defined the function with a SEXP argument, the code tests if this is a string or not and depending on this transforms that maturity in an actual date in two different ways. However, I cannot set a default value for the SEXP argument. It seems like a basic question but I have googled quite a bit and could not find anything on this.
Date CPPConvertDate(Date ParamDate, SEXP MaturityDate = 1) {
Date Result ;
const int type_Matu = TYPEOF(MaturityDate) ;
if (type_Matu == 16){
std::string MaturityDate_string = as<std::string>(MaturityDate) ;
//' DO STUFF
} else {
int MaturityDate_int = as<int>(MaturityDate) ;
//' DO OTHER STUFF
}
return (Result) ;
}
Compiler tells me "Cannot initialize a parameter of type SEXP with an R value of type int" so it is pretty clear that I cannot use 1 a default value for MaturityDate. If possible I would like to avoid having two different functions, one with int arguments and one with string argument.
Listen to the compiler because it is a source of wisdown. SEXP has no assignment from 1 as it is a union type -- which is why we have all those wrap() functions to return a SEXP given all possible inputs.
So if it is a Date, use a date type. I have been doing that in RQuantLib (which after all lead to to Rcpp) for well over a decade. If you need a mixed type for different behaviour then methinks you will have a hard time coming up with a default value either way.
Also: not "RCPP". Rcpp, please.

Implementation of modulus function on sage-math

I am implementing simple modulus function on sage jupitar notebook. The function is as follows:
Mod2(v,b)=(v+b*(q-1)/2) mod q mod 2
The function is wriiten in sage as :
def modulus(v,b):
q=12289
c=[]
for i in range(len(v)):
c.append(mod(((v[i]+b[i]*(q-1)//2)%q),2))
return c
The function is executed as :
dimension = 1024 # degree of polynomials
modulus = 12289
R.<X> = PolynomialRing(GF(modulus),) Gaussian field of integers
Y.<x> = R.quotient(X^(dimension) + 1) # Cyclotomic field
pi=Y.random_element()
c=Y.random_element()
xi=Y.random_element()
sj=Y.random_element()
rj=Y.random_element()
gj=Y.random_element()
kj=((pi*c+xi)*(sj*d+rj)+(2*c*gj))
# Now, We are making another list named mon and calling the modulus function
mon=[1,2,6,5,8]
modulus(kj.list(),mon)
I get following error while executing the above code.
TypeError: 'sage.rings.integer.Integer' object is not callable
This kind of error nearly always happens when you try to do something that Sage translates as 1(3). In this case, you have redefined something!
def modulus(v,b):
versus
modulus = 12289
You can't overload things this way in Python. Sage will replace what modulus refers to by that number; your function is just gone now. So when you do
modulus(kj.list(),mon)
you are trying to call 12289 as a function.
I suggest calling your other modulus modulus1 or something like that. Do it consistently, and this problem should disappear. Good luck.

printing string and calling recursive function

I am currently learning sml but I have one question that I can not find an answer for. I have googled but still have not found anything.
This is my code:
fun diamond(n) =
if(n=1) then (
print("*")
) else (
print("*")
diamond(n-1)
)
diamond(5);
That does not work. I want the code to show as many * as number n is and I want to do that with recursion, but I don't understand how to do that.
I get an error when I try to run that code. This is the error:
Standard ML of New Jersey v110.78 [built: Thu Aug 20 19:23:18 2015]
[opening a4_p2.sml] a4_p2.sml:8.5-9.17 Error: operator is not a
function [tycon mismatch] operator: unit in expression:
(print "*") diamond /usr/local/bin/sml: Fatal error -- Uncaught exception Error with 0 raised at
../compiler/TopLevel/interact/evalloop.sml:66.19-66.27
Thank you
You can do side effects in ML by using ';'
It will evaluate whatever is before the ';' and discard its result.
fun diamond(n) =
if(n=1)
then (print "*"; 1)
else (print "*"; diamond(n-1));
diamond(5);
The reason for the error is because ML is a strongly typed language that although you don't need to specify types explicitly, it will infer them based on environmental factors at compile time. For this reason, every evaluation of functions, statements like if else need to evaluate to an unambiguous singular type.
If you were allowed to do the following:
if(n=1)
then 1
else print "*";
then the compiler will get a different typing for the then and else branch respectively.
For the then branch the type would be int -> int whereas the type for the else branch would be int -> unit
Such a dichotomy is not allowed under a strongly typed language.
As you need to evaluate to a singular type, you will understand that ML does not support the execution of a block of instructions as we commonly see in other paradigms which transposed to ML naively would render something like this:
....
if(n=1)
then (print "1"
print "2"
)
else (print "3"
diamond(n-1)
)
...
because what type would the then branch evaluate to? int -> unit? Then what about the other print statement? A statement has to return a singular result(even it be a compound) so that would not make sense. What about int -> unit * unit? No problem with that except that syntactically speaking, you failed to communicate a tuple to the compiler.
For this reason, the following WOULD work:
fun diamond(n) =
if(n=1)
then (print "a", 1) /* A tuple of the type unit * int */
else diamond(n-1);
diamond(5);
As in this case you have a function of type int -> unit * int.
So in order to satisfy the requirement of the paradigm of strongly typed functional programming where we strive for building mechanisms that evaluate to one result-type, we thus need to communicate to the compiler that certain statements are to be executed as instructions and are not to be incorporated under the typing of the function under consideration.
For this reason, you use ';' to communicate to the compiler to simply evaluate that statement and discard its result from being incorporated under the type evaluation of the function.
As far as your actual objective is concerned, following is a better way of writing the function, diamond as type int -> string:
fun diamond(n) =
if(n=1)
then "*"
else "*" ^ diamond(n-1);
print( diamond(5) );
The above way is more for debugging purposes.

Resources