What do [0, rows) and [1, rows] mean? more specifically [ and ) - math

I understand that it's from 0 to rows and from 1 to rows, but which is including and which is excluding?

[ - including,
( - excluding
Example: [10, 15)
10, 11, 12, 13, 14
Example: (2, 4)
3

The [ is inclusive, ) is exclusive. So everything from 0 to rows, including 0, but not rows.
Sometimes this syntax is used instead: [0, rows[

The [ denotes a closed interval (i.e. inclusive) and the ) denotes an open interval (i.e. exclusive). So [0, 10) means 0 through 10, excluding 10.

Related

How can i filter a list by 2 conditions?

I'm new to prolog and i can't find a solution to filter list by 2 conditions, save result into 2 variables and then evaluate answer base on them.
In my case, if list contains more numbers that greater then 0, then numbers lesser then 0.
For example i get a list with elements:
checklist([-2, 3.3, 12, -10.1, 14, -11, 123]) # true
checklist([-2.1, -3, -4, 14, 16.7]) # false
checklist([11.5, 2.5, -34.1, -1]) # false
I'd write something like this in python:
bigger_count = 0
lesser_count = 0
for num in list:
if num > 0:
bigger_count += 1
elif num < 0:
lesser_count += 1
print(bigger_count > lesser_count)
Especially i doesn't understand how to work with 2 variables at one time.
https://www.swi-prolog.org/pldoc/doc_for?object=include/3
https://www.swi-prolog.org/pldoc/doc_for?object=convlist/3
If you have 2 conditions, you need to traverse the list twice, but is the complexity of code that can handle two different predicates worth the trouble?
Anyway, if you're writing from scratch, you can simplify your life by using DCGs:
filter(_Pred, []) --> [].
filter(Pred, [X|Xs]) -->
( { call(Pred, X) }
-> [X]
; []
),
filter(Pred, Xs).
filter(Pred, List, Result) :-
phrase(filter(Pred, List), Result).
even(X) :- 0 is X mod 2.
?- filter(even, [1,2,3,4,5], X).
X = [2, 4]
Another possible solution is:
check(List) :-
check(List, Balance),
Balance > 0.
check([], 0).
check([X|Xs], B) :-
check(Xs, B0),
( X > 0 -> B is B0 + 1
; X < 0 -> B is B0 - 1
; B is B0 ).
Examples:
?- check([-2, 3.3, 12, -10.1, 14, -11, 123]).
true.
?- check([-2.1, -3, -4, 14, 16.7]).
false.
?- check([11.5, 2.5, -34.1, -1]).
false.
?- check([1,-1]).
false.
The easiest way is to use a worker predicate that carries the required extra state.
checklist( Ns, P, N ) :- checklist(Ns, 0, 0, P, N )
checklist( [] , P , N , P , N ) .
checklist( [X|Xs] , P0 , N0 , P , N ) :- X > 0, P1 is P0+1, checklist(Xs,P1,N0,P,N).
checklist( [X|Xs] , P0 , N0 , P , N ) :- X < 0, B1 is N0+1, checklist(Xs,P0,N1,P,N).
If you add up all the values in the list, you'll get a positive or negative result which varies with how big the numbers are, instead of how many there are. There is a mathematical function sign or signum which turns all negative values into -1, and all positive values into +1, then you can add them up and if there were more positive inputs, the answer is positive, if there are more negative inputs, the answer is negative. Or they will cancel out and the sum will be 0.
If you maplist signthat over the inputs:
?- maplist(sign, [-2, 3.3, 12, -10.1, 14, -11, 123], X).
X = [-1, 1.0, 1, -1.0, 1, -1, 1]
Then:
?- sum_list(X, S).
S = 1.0
a positive result, so more positives than negatives in this case.
you could partition/4 the input list into the smaller vs larger values:
?- partition(>(0), [-2, 3.3, 12, -10.1, 14, -11, 123], Lesser, Greater).
Lesser = [-2, -10.1, -11],
Greater = [3.3, 12, 14, 123]
Then use length/2 and compare the result to see which one is longer.
(This might not be useful if any of the inputs are 0, they are not in your examples. I think this will use more memory to make a copy of the list.).

Most common term in a vector - PARI/GP

I feel like I'm being really stupid here as I would have thought there's a simple command already in Pari, or it should be a simple thing to write up, but I simply cannot figure this out.
Given a vector, say V, which will have duplicate entries, how can one determine what the most common entry is?
For example, say we have:
V = [ 0, 1, 2, 2, 3, 4, 6, 8, 8, 8 ]
I want something which would return the value 8.
I'm aware of things like vecsearch, but I can't see how that can be tweaked to make this work?
Very closely related to this, I want this result to return the most common non-zero entry, and some vectors I look at will have 0 as the most common entry. Eg: V = [ 0, 0, 0, 0, 3, 3, 5 ]. So whatever I execute here I would like to return 3.
I tried writing up something which would remove all zero terms, but again struggled.
The thing I have tried in particular is:
rem( v ) = {
my( c );
while( c = vecsearch( v, 0 ); #c, v = vecextract( v, "^c" ) ); v
}
but vecextract doesn't seem to like this set up.
If you can ensure all the elements are within the some fixed range then it is enough just to do the counting sorting with PARI/GP code like this:
counts_for(v: t_VEC, lower: t_INT, upper: t_INT) = {
my(counts = vector(1+upper-lower));
for(i=1, #v, counts[1+v[i]-lower]++);
vector(#counts, i, [i-1, counts[i]])
};
V1 = [0, 1, 2, 2, 3, 4, 6, 8, 8, 8];
vecsort(counts_for(V1, 0, 8), [2], 4)[1][1]
> 8
V2 = [0, 0, 0, 0, 3, 3, 5];
vecsort(counts_for(V2, 0, 5), [2], 4)[1][1]
> 0
You also can implement the following short-cut for the sake of convenience:
counts_for1(v: t_VEC) = {
counts_for(v, vecmin(v), vecmax(v))
};
most_frequent(v: t_VEC) = {
my(counts=counts_for1(v));
vecsort(counts, [2], 4)[1][1]
};
most_frequent(V1)
> 8
most_frequent(V2)
> 0
The function matreduce provides this in a more general setting: applied to a vector of objects, it returns a 2-column matrix whose first column contains the distinct objects and the second their multiplicity in the vector. (The function has a more general form that takes the union of multisets.)
most_frequent(v) = my(M = matreduce(v), [n] = matsize(M)); M[n, 1];
most_frequent_non0(v) =
{ my(M = matreduce(v), [n] = matsize(M), x = M[n, 1]);
if (x == 0, M[n - 1, 1], x);
}
? most_frequent([ 0, 1, 2, 2, 3, 4, 6, 8, 8, 8 ])
%1 = 8
? most_frequent([x, x, Mod(1,3), [], [], []])
%2 = []
? most_frequent_non0([ 0, 0, 0, 0, 3, 3, 5 ])
%3 = 5
? most_frequent_non0([x, x, Mod(1,3), [], [], []])
%4 = x
The first function will error out if fed an empty vector, and the second one if there are no non-zero entries. The second function tests for "0" using the x == 0 test (and we famously have [] == 0 in GP); for a more rigorous semantic, use x === 0 in the function definition.

Next number in the sequence || General approach

how can I find the next number in this sequence ,
1, 4, 7, 8, 13, 12, 9 , ?
How to check , given any sequence of numbers , feasible or not. Any general theory or approach is very much welcomed .
One method is to go to the Online Encyclopedia of Integer Sequences and enter your list of at least six or eight numbers into the box and see if that happens to be a known sequence. For your example this doesn't find a known sequence.
If that doesn't work then you can try Mathematica's FindFormula
p=FindFormula[{1, 4, 7, 8, 13, 12, 9}];
and then
p[1] returns 1, p[2] returns 4, p[3] returns 7... and p[8] returns 106, etc.
You can read the documentation on FindFormula and you can look at the formula p by using InputForm[p] where #1 represents a variable in the function p.
In general I think this is rarely going to produce the result that you are looking for.
seq = FindSequenceFunction[{1, 4, 7, 8, 13, 12, 9}, n]
(48 - 74 n - 14 n^2 + 11 n^3 - n^4)/(3 (-13 + 3 n))
Checking the 7th number
n = 7;
seq
9
The next number is a fraction, apparently
n = 8;
seq
32/11
Show[Plot[seq, {n, 1, 10}],
ListPlot[Table[seq, {n, 1, 10}]],
PlotRange -> {{0, 10}, {-20, 30}}, AxesOrigin -> {0, 0}]

Find all the factors of a number from the prime factors

Using Elliptic curve factorization (in Python) I am able to find the PRIME factors of a 50 digit number in ~0.5 sec. Is there any way I can convert the prime factors to the factors of the number?
What I have realized by testing on small digits (496 and 28), multiplying the prime factors together in a specific order. Then multiplying those numbers almost gives me the factors, but it is not very flexible because I have only gotten the formula of what I need to multiply together from small list of prime factors (1,2,3,5).
Here's my version, which computes the element-wise products of the powerset of the set of prime factors, keeping only those products that are unique:
def divisors(n, fs=[]):
if fs == []: fs = factors(n)
divs = [1]
for f in fs:
temp = divs[:]
for d in divs:
if f * d not in temp:
temp.append(f*d)
divs = temp
return sorted(divs)
And here it is in action:
>>> factors(496)
[2, 2, 2, 2, 31]
>>> divisors(496)
[1, 2, 4, 8, 16, 31, 62, 124, 248, 496]
>>> factors(28)
[2, 2, 7]
>>> divisors(28)
[1, 2, 4, 7, 14, 28]
If the number is factored into powers of primes, like p^a q^b r^c then the possible factors of the number are all numbers of the form p^x q^y r^z for 0 ≤ x ≤ a, 0 ≤ y ≤ b, and 0 ≤ r ≤ z.
Since you can have different numbers of prime factors, this is a little programming problem. Have fun.
Maybe you're looking for the product of each (unique) set in the powerset. So for 18=2*3*3 you want the product for each set in {{},{2},{3},{3},{2,3},{2,3},{3,3},{2,3,3}}, giving you {1, 2, 3, 3, 6, 9, 18}.
You can use sympy module like this:
import sympy
sympy.ntheory.factorint(4960) #Factorization.
sympy.ntheory.divisors(4960) #List all divisors.

Learning game programming (part 2) (math) [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 9 years ago.
Improve this question
So, it's been a few months since I wrote this question, since then I've toyed with "raw" C++ D3D, The Ogre and Irrlicht graphics engines and lately Microsoft XNA. I've built a few 2D games (mostly replicas of old stuff like tetris, astreoids, etc.) and made some (very) small steps into the 3D world in the above mentioned technologies.
I have little to no trouble creating the actual game logic, abstracting away object interactions to allow me to plug in different forms of control (computer, player, over network. etc.), doing threading or any of the other stuff I'm used to from my day to day work - which feels perfectly natural to me. I messed around very little with HLSL and particle effects (very very basic).
But 3D math involving Matrices and Vectors (and Quaternions(?) in Ogre3D, are these really needed?)... really gets me, I can follow examples (e.g. the Learning XNA 3.0 book I bought from O'Reilly, which is an awesome book btw) and I understand why and how something happens in the example, but when I try to do something myself I feel that I'm lacking the understanding of this type of math to be able to really get it and make it work by myself.
So I'm looking for resources on learning 3D math (mostly) and some Shader/Particle Effects books. I would prefer resources that are pedagogic and take it slow above something like a doctors thesis on vector math which will be way over my head. The ideal resource would be something that demonstrates it all in D3D.
Ok, a quick course in Matrix/Vector calculation:
A matrix is a collection of numbers ordered in a rectangular grid like:
[ 0, 1, 2 ]
[ 2, 3, 5 ]
[ 2, 1, 3 ]
[ 0, 0, 1 ]
The above matrix has 4 rows and 3 columns and as such is a 4 x 3 matrix.
A vector is a matrix with 1 row (a row vector) or 1 column (a column vector).
Normal numbers are called scalars to contrast with matrices.
It is also common to use capital letters for matrices and lowercase letters for scalars.
We can do basic calculation with matrices but there are some conditions.
Addition
Matrices can be added if they have the same dimensions. So a 2x2 matrix can be added to a 2x2 matrix but not to a 3x5 matrix.
[ 1, 2 ] + [ 2, 5 ] = [ 3, 7 ]
[ 2, 4 ] [ 0, 3 ] [ 2, 7 ]
You see that by addition each number at each cell is added to the number on the same position in the other matrix.
Matrix multiplication
Matrices can be multiplied, but this is a bit more complex. In order to multiply matrix A with matrix B, you need to multiply the numbers in each row if matrix A with each column in matrix B. This means that if you multiply an a x b matrix with a c x d matrix, b and c must be equal and the resulting matrix is a x d:
[1,2,3] x [4,6] = [1x4+2x2+3x2, 1x6+2x1+3x3 ] = [4+4+6, 6+2+9 ] = [14, 20]
[1,4,5] [2,1] [1x4+4x2+5x2, 1x6+4x1+5x3 ] [4+8+10, 6+4+15 ] [22, 25]
[2,3]
As you can see, with matrixes, A x B differs from B x A.
Matrix scalar multiplication
You can multiply a matrix with a scalar. In that case, each cell is multiplied with that number:
3 x [1,2] = [ 3, 6]
[4,7] [12,21]
Inverting a matrix
Matrix division is not possible, but you can create an inversion of a matrix such that A x A-inv is a matrix with all zero's except for that main diagonal:
[ 1, 0, 0 ]
[ 0, 1, 0 ]
[ 0, 0, 1 ]
Inverting a matrix can only be done with square matrices and it is a complex job that does not neccesary have a result.
Start with matrix A:
[ 1, 2, 3 ]
A = [ 1, 3, 4 ]
[ 2, 5, 1 ]
We add 3 extra columns and fill them with the unit matrix:
[ 1, 2, 3, 1, 0, 0 ]
[ 1, 3, 4, 0, 1, 0 ]
[ 2, 5, 1, 0, 0, 1 ]
Now we start with the first column. We need to subtract the first row from each other row such that the first column contains only zeroes except for the first row.
In order to do that we subtract the first row once from the second and twice from the third:
[ 1, 2, 3, 1, 0, 0 ]
[ 0, 1, 1,-1, 1, 0 ]
[ 0, 1,-5,-2, 0, 1 ]
Now we repeat this with the second column (twice from the first row and once from the third)
[ 1, 0, 1, 3,-2, 0 ]
[ 0, 1, 1,-1, 1, 0 ]
[ 0, 0,-6,-1,-1, 1 ]
For the third column, we have a slight problem. The pivot number is -6 and not 1. But we can solve this by multiplying the entire row with -1/6:
[ 1, 0, 1, 3, -2, 0 ]
[ 0, 1, 1, -1, 1, 0 ]
[ 0, 0, 1, 1/6, 1/6, -1/6 ]
And now we can subtract the third row from the first and the second:
[ 1, 0, 0, 17/6,-13/6, 1/6 ]
[ 0, 1, 0, -7/6, 5/6, 1/6 ]
[ 0, 0, 1, 1/6, 1/6, -1/6 ]
Ok now we have the inverse of A:
[ 17/6,-13/6, 1/6 ]
[ -7/6, 5/6, 1/6 ]
[ 1/6, 1/6, -1/6 ]
We can write this as:
[ 17,-13, 1 ]
1/6 * [ -7, 5, 1 ]
[ 1, 1, -1 ]
[ 1, 2, 3 ] [ 17,-13, 1 ] [ 6, 0, 0 ] [ 1, 0, 0 ]
A = [ 1, 3, 4 ] x [ -7, 5, 1 ] x 1/6 = 1/6 x [ 0, 6, 0 ] = [ 0, 1, 0 ]
[ 2, 5, 1 ] [ 1, 1, -1 ] [ 0, 0, 6 ] [ 0, 0, 1 ]
Hope this helps a bit.
Fredrik - the short answer is that, yes, you must learn Matrices and Vectors as they are the mathematical underpinnings for 3D work.
While Linear algebra is definitely not doctorate-level mathematics, it will take a bit of work. To get started, check out this book on Amazon: it looks like it is exactly what you are looking for. I haven't read this particular book (the one I used in grad school is a bit out of date) but it is particularly well rated.
One other thing: there are various 3D modeling engines that do this work for you on the market. The most famous of these is arguably the Source Engine from Valve. You can use this Engine (built for HalfLife2 & CounterStrike) to create some pretty sophisticated games while working above the level of 3D modeling. In fact, one of the most popular games on the Steam network, Garry's mod started with someone just playing with cool things you can do with the Steam Engine. Here's a link to a site that provides tutorials for building your own worlds using the Source Engine in case you are interested.
You definitely need to learn linear algebra. MIT released the whole class on youtube, for free. You can start from here. It's not that difficult, believe me! Have fun ;)
'Mathematics for Computer Graphics Applications' is an introductory level textbook and takes a classroom appropriate approach to all of the basic math that you need to be acquainted with for 3D programming (matrices and vectors mostly)
And a note regarding quaternions: They're very useful for certain applications. SLERP (Spherical Linear intERPolation) can be very handy for producing smooth/appealing camera movements (among other things). SLERP is a pain (expensive) to do with matrices, but cheap and easy with Quaternions. Learn to use and love them - even if you don't fully understand them.
For vectors specifically, an introductory text or course on linear algebra should be able to get you up to speed fairly quickly.

Resources