Smalltalk Vandermonde-matrix - smalltalk

Long in short it is a Vandermonde matrix and I have a problem to run a for in the second dimension of the array.
'add meg M-et majd N-et (enter kozotte)(az 1. sor az 1-es szam hatvanyai)' displayNl.
M := stdin nextLine asInteger.
N := stdin nextLine asInteger.
|tomb|
tomb := Array new: M.
x := 1.
y := 1.
a := M + 1.
b := N + 1.
x to: a do: [ :i|
tomb at:x put: (Array new: N) y to: b do: [ :j |
x at: y put: (x raisedTo: y - 1) ] ].
tomb printNl.

Here is a good way to create a matrix for which we have an expression of the generic entry aij:
Matrix class >> fromBlock: aBlock rows: n columns: m
| matrix |
matrix := self rows: n columns: m.
matrix indicesDo: [:i :j | | aij |
aij := aBlock value: i value: j.
matrix at: i at: j put: aij].
^matrix
With the above method you can now implement
Matrix class >> vandermonde: anArray degree: anInteger
^self
fromBlock: [:i :j | (anArray at: i) raisedTo: j - 1]
rows: anArray size
columns: anInteger + 1
EDIT
I just realized that in Pharo there is a way to create a matrix from the expression of its aij, it is named rows:columns:tabulate:, so my answer reduces to:
Matrix class >> vandermonde: anArray degree: anInteger
^self
rows: anArray size
columns: anInteger + 1
tabulate: [:i :j | (anArray at: i) raisedTo: j - 1]

Related

go benchmark and gc: B/op alloc/op

benchmark code:
func BenchmarkSth(b *testing.B) {
var x []int
b.ResetTimer()
for i := 0; i < b.N; i++ {
x = append(x, i)
}
}
result:
BenchmarkSth-4 50000000 20.7 ns/op 40 B/op 0 allocs/op
question/s:
where did 40 B/op come from? (any way of tracing + instructions is greatly appreciated)
how is it possible to have 40 B/op while having 0 allocs?
which one affects GC and how? (B/op or allocs/op)
is it really possible to have 0 B/op using append?
The Go Programming Language Specification
Appending to and copying slices
The variadic function append appends zero or more values x to s of
type S, which must be a slice type, and returns the resulting slice,
also of type S.
append(s S, x ...T) S // T is the element type of S
If the capacity of s is not large enough to fit the additional values,
append allocates a new, sufficiently large underlying array that fits
both the existing slice elements and the additional values. Otherwise,
append re-uses the underlying array.
For your example, on average, [40, 41) bytes per operation are allocated to increase the capacity of the slice when necessary. The capacity is increased using an amortized constant time algorithm: up to len 1024 increase to 2 times cap then increase to 1.25 times cap. On average, there are [0, 1) allocations per operation.
For example,
func BenchmarkMem(b *testing.B) {
b.ReportAllocs()
var x []int64
var a, ac int64
b.ResetTimer()
for i := 0; i < b.N; i++ {
c := cap(x)
x = append(x, int64(i))
if cap(x) != c {
a++
ac += int64(cap(x))
}
}
b.StopTimer()
sizeInt64 := int64(8)
B := ac * sizeInt64 // bytes
b.Log("op", b.N, "B", B, "alloc", a, "lx", len(x), "cx", cap(x))
}
Output:
BenchmarkMem-4 50000000 26.6 ns/op 40 B/op 0 allocs/op
--- BENCH: BenchmarkMem-4
bench_test.go:32: op 1 B 8 alloc 1 lx 1 cx 1
bench_test.go:32: op 100 B 2040 alloc 8 lx 100 cx 128
bench_test.go:32: op 10000 B 386296 alloc 20 lx 10000 cx 12288
bench_test.go:32: op 1000000 B 45188344 alloc 40 lx 1000000 cx 1136640
bench_test.go:32: op 50000000 B 2021098744 alloc 57 lx 50000000 cx 50539520
For op = 50000000,
B/op = floor(2021098744 / 50000000) = floor(40.421974888) = 40
allocs/op = floor(57 / 50000000) = floor(0.00000114) = 0
Read:
Go Slices: usage and internals
Arrays, slices (and strings): The mechanics of 'append'
'append' complexity
To have zero B/op (and zero allocs/op) for append, allocate a slice with sufficient capacity before appending.
For example, with var x = make([]int64, 0, b.N),
func BenchmarkZero(b *testing.B) {
b.ReportAllocs()
var x = make([]int64, 0, b.N)
var a, ac int64
b.ResetTimer()
for i := 0; i < b.N; i++ {
c := cap(x)
x = append(x, int64(i))
if cap(x) != c {
a++
ac += int64(cap(x))
}
}
b.StopTimer()
sizeInt64 := int64(8)
B := ac * sizeInt64 // bytes
b.Log("op", b.N, "B", B, "alloc", a, "lx", len(x), "cx", cap(x))
}
Output:
BenchmarkZero-4 100000000 11.7 ns/op 0 B/op 0 allocs/op
--- BENCH: BenchmarkZero-4
bench_test.go:51: op 1 B 0 alloc 0 lx 1 cx 1
bench_test.go:51: op 100 B 0 alloc 0 lx 100 cx 100
bench_test.go:51: op 10000 B 0 alloc 0 lx 10000 cx 10000
bench_test.go:51: op 1000000 B 0 alloc 0 lx 1000000 cx 1000000
bench_test.go:51: op 100000000 B 0 alloc 0 lx 100000000 cx 100000000
Note the reduction in benchmark CPU time from around 26.6 ns/op to around 11.7 ns/op.

Combinations WITH repetitions in Smalltalk

I need to generate all the possible combinations of N numbers including repetitions.
Problem input: I have N cells where I can put one number in the interval 0 to: 9, in each cell.
Wrong solution (with N = 4):
(0 to: 3) permutationsDo: [ : each | Transcript cr; show: each printString].
Does not includes #(0 0 0 0) , #(1 1 1 1) , #(2 2 2 2), etc.
Expected output (with N = 2, and range 1-4 for the sake of brevity):
#(1 1)
#(2 2)
#(3 3)
#(4 4)
#(2 1)
#(3 2)
#(4 3)
#(1 4)
#(3 1)
#(4 2)
#(1 3)
#(2 4)
#(4 1)
#(1 2)
#(2 3)
#(3 4)
Here are a couple of selectors with which you could extend SequenceableCollection. That's the class where permutationsDo: is defined and is inherited, ultimately, by the Interval class.
Category "enumerating":
enumerationsDo: aBlock
| anArray |
anArray := Array new: self size.
self enumerateWithSize: (self size) in: anArray do: [ :each | aBlock value: each ]
Category "private":
enumerateWithSize: aSize in: anArray do: aBlock
(aSize = 1)
ifTrue: [
self do: [ :each |
aBlock value: (anArray at: (self size - aSize + 1) put: each ; yourself) ] ]
ifFalse: [
self do: [ :each |
self enumerateWithSize: (aSize - 1) in: anArray do: [ :eachArray |
aBlock value: (eachArray at: (self size - aSize + 1) put: each ; yourself) ] ] ]
So now you can do:
(0 to: 2) enumerationsDo: [ :each | Transcript show: each printString ; cr ]
Which yields:
#(0 0 0)
#(0 0 1)
#(0 0 2)
#(0 1 0)
#(0 1 1)
#(0 1 2)
#(0 2 0)
#(0 2 1)
#(0 2 2)
#(1 0 0)
#(1 0 1)
#(1 0 2)
#(1 1 0)
#(1 1 1)
#(1 1 2)
#(1 2 0)
#(1 2 1)
#(1 2 2)
#(2 0 0)
#(2 0 1)
#(2 0 2)
#(2 1 0)
#(2 1 1)
#(2 1 2)
#(2 2 0)
#(2 2 1)
#(2 2 2)
This selector operates "symmetrically" like the existing permutationsDo: selector does, which is the number of elements in the resulting arrays (number of choices) is the same as the number of values in the collection.
You can easily go from that to a more general solution:
Under "enumerating":
enumerationsDo: aBlock
self enumerationsOfSize: (self size) do: aBlock
enumerationsOfSize: aSize do: aBlock
| anArray |
anArray := Array new: aSize.
self enumerateWithSize: aSize subSize: aSize in: anArray do: [ :each | aBlock value: each ]
Under "private":
enumerateWithSize: aSize subSize: sSize in: anArray do: aBlock
(aSize < sSize)
ifTrue: [ ^self error: 'subSize cannot exceed array size' ].
(sSize < 1)
ifTrue: [ ^self error: 'sizes must be positive' ].
(sSize = 1)
ifTrue: [
self do: [ :each |
aBlock value: (anArray at: (aSize - sSize + 1) put: each ; yourself) ] ]
ifFalse: [
self do: [ :each |
self enumerateWithSize: aSize subSize: (sSize - 1) in: anArray do: [ :eachArray |
aBlock value: (eachArray at: (aSize - sSize + 1) put: each ; yourself) ] ] ]
Here's an example:
(1 to: 3) enumerationsOfSize: 2 do: [ :e | Transcript show: e printString ; cr ]
Which yields:
#(1 1)
#(1 2)
#(1 3)
#(2 1)
#(2 2)
#(2 3)
#(3 1)
#(3 2)
#(3 3)
Let me implement this in SequenceableCollection for the sake of simplicity:
nextCombination09
| j |
j := self findLast: [:ai | ai < 9] ifAbsent: [^nil].
j + 1 to: self size do: [:i | self at: i put: 0].
self at: j put: (self at: j) + 1
The idea is the following: Use the lexicographic order to sort all combinations. In other words:
(a1, ..., an) < (b1, ..., bn)
if ai = bi for all i below some index j where aj < bj.
With this order the first combination is (0, ..., 0) and the last one (9, ..., 9).
Moreover, given a combination (a1, ..., an) the next one in this order is the one that adds 1 to the lowest preeminent index, this is the last index j where aj < 9. For example the next to (2, 3, 8, 9) is (2, 3, 9, 9) as there can't be anything in between.
Once we get to (9, ..., 9) we are done, and answer with nil.
Be aware that the method above modifies the receiver, which is why we have to copy in the script below.
Here is the script that produces all combinations (n is your N)
n := <whatever>
array := Array new: n withAll: 0.
combinations := OrderedCollection new: (10 raisedTo: n).
[
combinations add: array copy.
array nextCombination09 notNil] whileTrue.
^combinations
ADDENDUM
The same technique can be used for other problems of similar nature.

Nested "if" (AKA "switch") in Smalltalk (Pharo)

I need to populate the matrix (stored as an array of arrays) with some values. The matrix is a Jacobian for a simple diffusion problem and looks like this:
J(1,1) = 1, J(N,N)=0
and for 1<n<N:
J(n,n) = -2k/dx^2 - 2*c(n)
J(n,n-1)=J(n,n+1) = k/dx^2
the rest of the matrix entries are zeros.
So far I have this monstrosity:
(1 to: c size) collect: [ :n |
(1 to: c size) collect: [ :m |
n = 1 | (n = c size)
ifTrue: [ m = n ifTrue: [ 1.0 ] ifFalse: [ 0.0 ] ]
ifFalse: [ m = n
ifTrue: [ -2.0 * k / dx squared - (2.0 * (c at: n)) ]
ifFalse: [ m = (n-1) | (m = (n+1))
ifTrue: [ k / dx squared ]
ifFalse: [ 0.0 ] ] ]
] ]
Notice the nested "if-statements" (Smalltalk equivalents). This works. But, is there, perhaps, a more elegant way of doing the same thing? As it stands now, it is rather unreadable.
n := c size.
Matrix
new: n
tabulate: [:i :j | self jacobianAtRow: i column: j]
where
jacobianAtRow: i column: j
n := c size.
(i = 1 or: [i = n]) ifTrue: [^j = i ifTrue: [1.0] ifFalse [0.0]].
j = i ifTrue: [^-2.0 * k / dx squared - (2.0 * (c at: i))].
(j = (i - 1) or: [j = (i + 1)]) ifTrue: [^k / dx squared].
^0.0
Basically, the general idea is this: whenever you find nested ifs, factor out that piece of code to a method by itself and transform the nesting into a cases-like enumeration that returns a value at every possibility.
For readability's sake I would consider sacrificing the extra O(n) time and avoid IFs altogether (which just make it even faster...).
J(N,N) = 0
J(1,1) = 1
//and for 1<n<N:
J(n,n) = Y(n)
J(n,m-1) = J(n,m+1) = X
What this tells me is that the whole matrix looks something like this
( 1 X 0 0 0 )
( X Y X 0 0 )
( 0 X Y X 0 )
( 0 0 X Y X )
( 0 0 0 X 0 )
Which means that I can create the whole matrix with just zeros, and then change the diagonal and neighboring diagonals.
jNM := [ k / dx squared ].
jNN := [ :n | -2.0 * k / dx squared - (2.0 * (c at: n)) ].
n := c size.
m := Matrix
new: n
tabulate: [:i :j | 0 ].
(1 to: n - 1) do: [ :i |
m at: i at: i put: (jNN value: i).
m at: i + 1 at: i put: jnM value.
m at: i at: i + 1 put: jnM value.
].
m at: 1 at: 1 put: 1.
Note: I'm not familiar with the math behind this but the value for J(n,m-1) seems like a constant to me.
Note 2: I'm putting the values at i + 1 indexes, because I am starting at position 1;1, but you can start from the opposite direction and have i-1.

Haskell, function works when using numbers, but not with variables

I'm using ghci and I'm having a problem with a function for getting the factors of a number.
The code I would like to work is:
let factors n = [x | x <- [1..truncate (n/2)], mod n x == 0]
It doesn't complain when I then hit enter, but as soon as I try to use it (with 66 in this case) I get this error message:
Ambiguous type variable 't0' in the constraints:
(Integral t0)
arising from a use of 'factors' at <interactive>:30:1-10
(Num t0) arising from the literal '66' at <interactive>:30:12-13
(RealFrac t0)
arising from a use of 'factors' at <interactive:30:1-10
Probable fix: add a type signature that fixes these type variable(s)
In the expression: factors 66
In the equation for 'it': it = factors 66
The following code works perfectly:
let factorsOfSixtySix = [x | x <- [1..truncate (66/2)], mod 66 x == 0]
I'm new to haskell, and after looking up types and typeclasses, I'm still not sure what I'm meant to do.
Use div for integer division instead:
let factors n = [x | x <- [1.. n `div` 2], mod n x == 0]
The problem in your code is that / requires a RealFrac type for n while mod an Integral one. This is fine during definition, but then you can not choose a type which fits both constraints.
Another option could be to truncate n before using mod, but is more cumbersome. After all, you do not wish to call factors 6.5, do you? ;-)
let factors n = [x | x <- [1..truncate (n/2)], mod (truncate n) x == 0]
If you put a type annotation on this top-level bind (idiomatic Haskell), you get different, possibly more useful error messages.
GHCi> let factors n = [x | x <- [1..truncate (n/2)], mod n x == 0]
GHCi> :t factors
factors :: (Integral t, RealFrac t) => t -> [t]
GHCi> let { factors :: Double -> [Double]; factors n = [x | x <- [1..truncate (n/2)], mod n x == 0]; }
<interactive>:30:64:
No instance for (Integral Double) arising from a use of `truncate'
Possible fix: add an instance declaration for (Integral Double)
In the expression: truncate (n / 2)
In the expression: [1 .. truncate (n / 2)]
In a stmt of a list comprehension: x <- [1 .. truncate (n / 2)]
GHCi> let { factors :: Integer -> [Integer]; factors n = [x | x <- [1..truncate (n/2)], mod n x == 0]; }
<interactive>:31:66:
No instance for (RealFrac Integer) arising from a use of `truncate'
Possible fix: add an instance declaration for (RealFrac Integer)
In the expression: truncate (n / 2)
In the expression: [1 .. truncate (n / 2)]
In a stmt of a list comprehension: x <- [1 .. truncate (n / 2)]
<interactive>:31:77:
No instance for (Fractional Integer) arising from a use of `/'
Possible fix: add an instance declaration for (Fractional Integer)
In the first argument of `truncate', namely `(n / 2)'
In the expression: truncate (n / 2)
In the expression: [1 .. truncate (n / 2)]
I am new to Haskell so please forgive my courage to come up with an answer here but recently i have done this as follows;
factors :: Int -> [Int]
factors n = f' ++ [n `div` x | x <- tail f', x /= exc]
where lim = truncate (sqrt (fromIntegral n))
exc = ceiling (sqrt (fromIntegral n))
f' = [x | x <- [1..lim], n `mod` x == 0]
I believe it's more efficient. You will notice if you do like;
sum (factors 33550336)

Mathematica solving complex equation

If I have a complex equation in the form of
Solve[z^2 + 9 - 1.5 E^[-tz]==0, z]
where z = x + I y
where x , y and t are all assumed to be real.
How do I tell Mathematica 9 to separate the real and imaginary parts to make
two equations in the form of
Re[z]==0, Im[z]==0.
I try this
myConjugate[eqn_Equal] := myConjugate /# eqn
myConjugate[expr_] := expr /. {I -> -I, a_Complex :> Conjugate[a]}
myRe[eqn_Equal] := myRe /# eqn
myRe[expr_] := (expr + myConjugate[expr])/2
myIm[eqn_Equal] := myIm /# eqn
myIm[expr_] := (expr - myConjugate[expr])/(2 I)
and
{myRe[#], myIm[#]} &[(x + I y)^2 + 9 - 1.5 E[- t (x+ I y)] == 0]