MathNet Matrix MapIndexInplace confusion about arguments - math.net

The Matrix function MapIndexInplace is documented to take a Func (int, int, float, float). I don't understand what the second float value is. Can anyone explain?

The Func<int,int,float,float> delegate represents a function with two integers and a float as arguments and a float as return value. So the second float represents the function's return value.
MapIndexInplace will call the provided function of this type signature for each (or optionally each non-zero) matrix element with three arguments (index i, index j, current value v) and replace the matrix element value with the value returned by the called function.

Related

why don't we need to pass in a function as an argument for this decorator?

I have a decorator here which takes a number x as a input and multiplies it by the result of the function f_(*k). There is nothing wrong with the code it works perfectly. But the question is, when we use sq(n) how does this decorator take sq(n) and multiply it by 3? how does the decorator know to take the result of the function sq(n) and multiply it by 3. Because a parameter for a function was not given or in other words, how does it substitute f_(*k) for sq(n) because sq(n) was not given as an argument.
def multiply(x):
def multiply_x(f):
def f_(*k):
return x*f(*k)
return f_
return multiply_x
#multiply(3)
def sq(n):
return n*n
#decorator(arg) is just a nice way to say func = decorator(arg)(func)
When you pass in the argument to the decorator, you are returning a completely new function (multiply_x) as the return value from the decorator multiply and replacing the identifier sq with it.
This function you just returned then takes the original function sq which now becomes the f parameter inside the inner function.
Now when you do sq(n) you actually call the inner f_(n). This function returns x (the 3 you passed in as the argument to your decorator) times the result of calling the function f (which was the original sq function)
I hope this somewhat clears things up

Rcpp: continued fractions and precision [duplicate]

How come that in the following snippet
int a = 7;
int b = 3;
double c = 0;
c = a / b;
c ends up having the value 2, rather than 2.3333, as one would expect. If a and b are doubles, the answer does turn to 2.333. But surely because c already is a double it should have worked with integers?
So how come int/int=double doesn't work?
This is because you are using the integer division version of operator/, which takes 2 ints and returns an int. In order to use the double version, which returns a double, at least one of the ints must be explicitly casted to a double.
c = a/(double)b;
Here it is:
a) Dividing two ints performs integer division always. So the result of a/b in your case can only be an int.
If you want to keep a and b as ints, yet divide them fully, you must cast at least one of them to double: (double)a/b or a/(double)b or (double)a/(double)b.
b) c is a double, so it can accept an int value on assignement: the int is automatically converted to double and assigned to c.
c) Remember that on assignement, the expression to the right of = is computed first (according to rule (a) above, and without regard of the variable to the left of =) and then assigned to the variable to the left of = (according to (b) above). I believe this completes the picture.
With very few exceptions (I can only think of one), C++ determines the
entire meaning of an expression (or sub-expression) from the expression
itself. What you do with the results of the expression doesn't matter.
In your case, in the expression a / b, there's not a double in
sight; everything is int. So the compiler uses integer division.
Only once it has the result does it consider what to do with it, and
convert it to double.
When you divide two integers, the result will be an integer, irrespective of the fact that you store it in a double.
c is a double variable, but the value being assigned to it is an int value because it results from the division of two ints, which gives you "integer division" (dropping the remainder). So what happens in the line c=a/b is
a/b is evaluated, creating a temporary of type int
the value of the temporary is assigned to c after conversion to type double.
The value of a/b is determined without reference to its context (assignment to double).
In C++ language the result of the subexpresison is never affected by the surrounding context (with some rare exceptions). This is one of the principles that the language carefully follows. The expression c = a / b contains of an independent subexpression a / b, which is interpreted independently from anything outside that subexpression. The language does not care that you later will assign the result to a double. a / b is an integer division. Anything else does not matter. You will see this principle followed in many corners of the language specification. That's juts how C++ (and C) works.
One example of an exception I mentioned above is the function pointer assignment/initialization in situations with function overloading
void foo(int);
void foo(double);
void (*p)(double) = &foo; // automatically selects `foo(fouble)`
This is one context where the left-hand side of an assignment/initialization affects the behavior of the right-hand side. (Also, reference-to-array initialization prevents array type decay, which is another example of similar behavior.) In all other cases the right-hand side completely ignores the left-hand side.
The / operator can be used for integer division or floating point division. You're giving it two integer operands, so it's doing integer division and then the result is being stored in a double.
This is technically a language-dependent, but almost all languages treat this subject the same. When there is a type mismatch between two data types in an expression, most languages will try to cast the data on one side of the = to match the data on the other side according to a set of predefined rules.
When dividing two numbers of the same type (integers, doubles, etc.) the result will always be of the same type (so 'int/int' will always result in int).
In this case you have
double var = integer result
which casts the integer result to a double after the calculation in which case the fractional data is already lost. (most languages will do this casting to prevent type inaccuracies without raising an exception or error).
If you'd like to keep the result as a double you're going to want to create a situation where you have
double var = double result
The easiest way to do that is to force the expression on the right side of an equation to cast to double:
c = a/(double)b
Division between an integer and a double will result in casting the integer to the double (note that when doing maths, the compiler will often "upcast" to the most specific data type this is to prevent data loss).
After the upcast, a will wind up as a double and now you have division between two doubles. This will create the desired division and assignment.
AGAIN, please note that this is language specific (and can even be compiler specific), however almost all languages (certainly all the ones I can think of off the top of my head) treat this example identically.
For the same reasons above, you'll have to convert one of 'a' or 'b' to a double type. Another way of doing it is to use:
double c = (a+0.0)/b;
The numerator is (implicitly) converted to a double because we have added a double to it, namely 0.0.
The important thing is one of the elements of calculation be a float-double type. Then to get a double result you need to cast this element like shown below:
c = static_cast<double>(a) / b;
or
c = a / static_cast(b);
Or you can create it directly::
c = 7.0 / 3;
Note that one of elements of calculation must have the '.0' to indicate a division of a float-double type by an integer. Otherwise, despite the c variable be a double, the result will be zero too (an integer).

Fortran function that returns scalar OR array depending on input

I'm trying to crate a function in Fortran (95) that that will have as input a string (test) and a character (class). The function will compare each character of test with the character class and return a logical that is .true. if they are of the same class1 and .false. otherwise.
The function (and the program to run it) is defined below:
!====== WRAPPER MODULE ======!
module that_has_function
implicit none
public
contains
!====== THE ACTUAL FUNCTION ======!
function isa(test ,class )
implicit none
logical, allocatable, dimension(:) :: isa
character*(*) :: test
character :: class
integer :: lt
character(len=:), allocatable :: both
integer, allocatable, dimension(:) :: intcls
integer :: i
lt = len_trim(test)
allocate(isa(lt))
allocate(intcls(lt+1))
allocate(character(len=lt+1) :: both)
isa = .false.
both = class//trim(test)
do i = 1,lt+1
select case (both(i:i))
case ('A':'Z'); intcls(i) = 1! uppercase alphabetic
case ('a':'a'); intcls(i) = 2! lowercase alphabetic
case ('0':'9'); intcls(i) = 3! numeral
case default; intcls(i) = 99! checks if they are equal
end select
end do
isa = intcls(1).eq.intcls(2:)
return
end function isa
end module that_has_function
!====== CALLER PROGRAM ======!
program that_uses_module
use that_has_function
implicit none
integer :: i
i = 65
! Reducing the result of "isa" to a scalar with "all" works:
! V-V
do while (all(isa(achar(i),'A')))
print*, achar(i)
i = i + 1
end do
! Without the reduction it doesn''t:
!do while (isa(achar(i),'A'))
! print*, achar(i)
! i = i + 1
!end do
end program that_uses_module
I would like to use this function in do while loops, for example, as it is showed in the code above.
The problem is that, for example, when I use two scalars (rank 0) as input the function still returns the result as an array (rank 1), so to make it work as the condition of a do while loop I have to reduce the result to a scalar with all, for example.
My question is: can I make the function conditionally return a scalar? If not, then is it possible to make the function work with vector and scalar inputs and return, respectively, vector and scalar outputs?
1. What I call class here is, for example, uppercase or lowercase letters, or numbers, etc. ↩
You can not make the function conditionally return a scalar or a vector.
But you guessed right, there is a solution. You will use a generic function.
You write 2 functions, one that takes scalar and return scalar isas, the 2nd one takes vector and return vector isav.
From outside of the module you will be able to call them with the same name: isa. You only need to write its interface at the beginning of the module:
module that_has_function
implicit none
public
interface isa
module procedure isas, isav
end interface isa
contains
...
When isa is called, the compiler will know which one to use thanks to the type of the arguments.
The rank of a function result cannot be conditional on the flow of execution. This includes selection by evaluating an expression.
If reduction of a scalar result is too much, then you'll probably be horrified to see what can be done instead. I think, for instance, of derived types and defined operations.
However, I'd consider it bad design in general for the function reference to be unclear in its rank. My answer, then, is: no you can't, but that's fine because you don't really want to.
Regarding the example of minval, a few things.1 As noted in the comment, minval may take a dim argument. So
integer :: X(5,4) = ...
print *, MINVAL(X) ! Result a scalar
print *, MINVAL(X,dim=1) ! Result a rank-1 array
is in keeping with the desire of the question.
However, the rank of the function result is still "known" at the time of referencing the function. Simply having a dim argument means that the result is an array of rank one less than the input array rather than a scalar. The rank of the result doesn't depend on the value of the dim argument.
As noted in the other answer, you can have similar functionality with a generic interface. Again, the resolved specific function (whichever is chosen) will have a result of known rank at the time of reference.
1 The comment was actually about minloc but minval seems more fitting to the topic.

How to write a function max_and_min that accepts a tuple containing integer elements as an argument?

Functions can only return a single value but sometimes, we may want functions to return multiple values. Tuples can come in handy in such cases. We can create a tuple containing multiple values and return the tuple instead of a single value.
Write a function max_and_min that accepts a tuple containing integer elements as an argument and returns the largest and smallest integer within the tuple. The return value should be a tuple containing the largest and smallest value, in that order.
for example: max_and_min((1, 2, 3, 4, 5)) = (5, 1)
I am told to use an iteration to loop through each value of the tuple parameter to find the maximum and minimum values. Also, I must use Python 3.x.
How do I do this? I am really clueless. Thanks for your help!
def max_and_min(values):
# Write your code here
You are looking to pass a variable number of arguments to a function. In python, you can get multiple arguments passed at invocation with the * notation:
def max_and_min(*arg):
return (max(arg), min(arg))
Note that the Python 3 min and max functions themselves accept a variable number of arguments.

swift println float using string

I wish to ask a conceptual question. My code is to print an array of float values of 5 decimal places onto the console. Why must it be String instead of Float? Ans[y] is an array of type float.
println(String(format: "%.5f", Ans[y]))
Instead of Float
println(Float(format: "%.5f", Ans[y]))
Float gives an error of extra argument 'format' in call
You can use map() to format your Float array as string array. Btw you should give it a name starting with a lowercase letter. Try doing as follow:
let floatArray:[Float] = [1.23456,3.21098,2.78901]
let formattedArray = floatArray.map{String(format: "%.5f", $0)}
println(formattedArray) // "[1.23456, 3.21098, 2.78901]"
It's just a matter of understanding what your words mean. String is an object type (a struct). Float is an object type (a struct). The syntax Thing(...) calls a Thing initializer - it creates a new object of type Thing and calls an initializer method init(...). That's what you're doing when you say String(...) and Float(...).
Well, there is a String init(format:) initializer (it actually comes from Foundation NSString, to which String is bridged), but there is no Float init(format:) initializer - the Float struct doesn't declare any such thing. So in the second code you're calling a non-existent method.
You can use NSLog instead of println. NSLog is still in the foundation class and has the flexibility of specifying the exact format you need.

Resources