text stringlengths 0 27.6k | python int64 0 1 | DeepLearning or NLP int64 0 1 | Other int64 0 1 | Machine Learning int64 0 1 | Mathematics int64 0 1 | Trash int64 0 1 |
|---|---|---|---|---|---|---|
I have two vectors in a game. One vector is the player, one vector is an object. I also have a vector that specifies the direction the player if facing. The direction vector has no z part. It is a point that has a magnitude of 1 placed somewhere around the origin.
I want to calculate the angle between the direction the soldier is currently facing and the object, so I can correctly pan some audio (stereo only).
The diagram below describes my problem. I want to calculate the angle between the two dashed lines. One dashed line connects the player and the object, and the other is a line representing the direction the player is facing from the point the player is at.
At the moment, I am doing this (assume player, object and direction are all vectors with 3 points, x, y and z):
Vector3d v1 = direction;
Vector3d v2 = object - player;
v1.normalise();
v2.normalise();
float angle = acos(dotProduct(v1, v2));
But it seems to give me incorrect results. Any advice?
Test of code:
Vector3d soldier = Vector3d(1.f, 1.f, 0.f);
Vector3d object = Vector3d(1.f, -1.f, 0.f);
Vector3d dir = Vector3d(1.f, 0.f, 0.f);
Vector3d v1 = dir;
Vector3d v2 = object - soldier;
long steps = 360;
for (long step = 0; step < steps; step++) {
float rad = (float)step * (M_PI / 180.f);
v1.x = cosf(rad);
v1.y = sinf(rad);
v1.normalise();
float dx = dotProduct(v2, v1);
float dy = dotProduct(v2, soldier);
float vangle = atan2(dx, dy);
}
| 0 | 0 | 0 | 0 | 1 | 0 |
Given an arbitrary sequence of points in space, how would you produce a smooth continuous interpolation between them?
2D and 3D solutions are welcome. Solutions that produce a list of points at arbitrary granularity and solutions that produce control points for bezier curves are also appreciated.
Also, it would be cool to see an iterative solution that could approximate early sections of the curve as it received the points, so you could draw with it.
| 0 | 0 | 0 | 0 | 1 | 0 |
Suppose you have a set of nodes connected into a tree structure with one root node and any node may have any number of child nodes.
You can only traverse the tree starting at the root node or from your current position along direct connections. I.e., no random access to a specific node, but the structure of the graph is already known and fits in memory.
Each node has a must-revisit time which is not revealed to you. The must-revisit time is calculated [where i = time interval since last visit] as (now + a + i*b + (i*c)^2). The parameters a, b and c have different values for each node but each will always generally be within the same order of magnitude across different nodes.
If you revisit a node past after its must-revisit time has passed it will reset so that the must-revisit time after that visit is calculated as (now + a) per the formula above. If you traverse to a node it will be revealed to you whether you have past the must-revisit time or not, but you will not know what it was or what the values or a, b or c are.
Your goal is to choose a strategy to traverse to and revisit each node in the tree over time so that no node is past its must-revisit time and minimize the number of traversal operations overall. Revisiting a node too early is inefficient, but revisiting a node past its must-revisit time is highly inefficient. Ideally you want to hit each node just before its must-revisit time or if you need to in order to traverse to another node.
| 0 | 0 | 0 | 1 | 0 | 0 |
I have an small physics toy application I am developing. It works fine except the particles will not push each other away, only pull towards, I debugged that sub going through it command by command and realised the value 'H' would not change, what ever it was set to during the first pass through the sub is what it kept, the only way to change this value is to manually set it i.e 'h = 1'. Once the calculation is redone on the 'H' value it resets to what it was previously, even though the x1,y1,x2,y2 are all different, thus meaning H should be different.
I think it is me that has made a mathematical mistake somewhere, but I cannot see where it is. I need a fresh pair of eyes to look over my work. Please let me know if you find anything.
Thanks.
Public Sub movenodes()
For i As Integer = 0 To connectionnumber
If connections(i).exists = True Then
Dim n1x As Integer
Dim n2x As Integer
Dim n1y As Integer
Dim n2y As Integer
Dim h As Integer
n1x = nodes(connections(i).node1).x
n2x = nodes(connections(i).node2).x
n1y = nodes(connections(i).node1).y
n2y = nodes(connections(i).node2).y
h = 1
h = Math.Sqrt(((nodes(connections(i).node1).x + nodes(connections(i).node2).x) ^ 2) + ((nodes(connections(i).node1).y + nodes(connections(i).node2).y) ^ 2))
Me.Text = nodes(connections(i).node1).x & " " & nodes(connections(i).node1).y & " " & h
If h > connections(i).happy Then
If n1x > n2x Then
nodes(connections(i).node1).hspeed -= 0.1
nodes(connections(i).node2).hspeed += 0.1
ElseIf n1x < n2x Then
nodes(connections(i).node1).hspeed += 0.1
nodes(connections(i).node2).hspeed -= 0.1
End If
If n1y > n2y Then
nodes(connections(i).node1).vspeed -= 0.1
nodes(connections(i).node2).vspeed += 0.1
ElseIf n1y < n2y Then
nodes(connections(i).node1).vspeed += 0.1
nodes(connections(i).node2).vspeed -= 0.1
End If
ElseIf h < connections(i).happy Then
MsgBox("")
If n1x > n2x Then
nodes(connections(i).node1).hspeed += 0.5
nodes(connections(i).node2).hspeed -= 0.5
ElseIf n1x < n2x Then
nodes(connections(i).node1).hspeed -= 0.5
nodes(connections(i).node2).hspeed += 0.5
End If
If n1y > n2y Then
nodes(connections(i).node1).vspeed += 0.5
nodes(connections(i).node2).vspeed -= 0.5
ElseIf n1y < n2y Then
nodes(connections(i).node1).vspeed -= 0.5
nodes(connections(i).node2).vspeed += 0.5
End If
End If
End If
Next
End Sub
| 0 | 0 | 0 | 0 | 1 | 0 |
I am looking for an (almost everywhere) differentiable function f(p1, p2, p3, p4) that given four points will give me a scale-agnostic measure for co-planarity. It is zero if the four points lie on the same plane and positive otherwise. Scale-agnostic means that, when I uniformly scale all points the planarity measure will return the same.
I came up with something that is quite complex and not easy to optimize. Define u=p2-p1, v=p3-p1, w=p4-p1. Then the planarity measure is:
[(u x v) * w]² / (|u x v|² |w|²)
where x means cross product and '*' means dot product.
The numerator is simply (the square of) the volume of the tetrahedron defined by the four points, and the denominator is a normalizing factor that makes this measure become simply the cosine of an angle. Because angles do not changed under uniform scale, this function satisfies all my requirements.
Does anybody know of something simpler?
Alex.
Edit:
I eventually used an Augmented Lagrangian method to perform optimization, so I don't need it to be scale agnostic. Just using the constraint (u x v) * w = 0 is enough, as the optimization procedure finds the correct Lagrange multiplier to compensate for the scale.
| 0 | 0 | 0 | 0 | 1 | 0 |
I've been working on testing various solutions for a Khmer Unicode Wordbreaker (Khmer does not have spaces between words which makes spell checking and grammar checking difficult, as well as converting from legacy Khmer into Khmer Unicode).
I was given some source code which is now online ( http://www.whitemagicsoftware.com/software/java/wordsplit/ ) that seems promising. The author was kind enough to give the source, but he is very busy writing a book and is unable to troubleshoot.
I am testing the code on a very small scale, and I am having trouble with the output.
Here is the input:
ជាដែលនឹងបានមាន
Here's the resulting output:
ជារ���លនឹងបានមាន,ជា រ���ល នឹង បាន
មាន
The words are actually split correctly, but one word is jumbled.
The output should look like this:
ជាដែលនឹងបានមាន, ជា ដែល នឹង បាន មាន
Does anyone have an insight as to why the output is garbled?
Here's the code with a very small Khmer lexicon and words to be split: http://www.sbbic.org/khmerwordsplit.zip
And here's how to run it:
java -jar wordsplit.jar
khmerlexicon.csv khmercolumns.txt >>
results.txt
I am very grateful to the stackoverflow community for all the help you have provided with this project so far - I hope a solution is soon to be found!
| 0 | 1 | 0 | 0 | 0 | 0 |
I am looking to develop some code that will be able to by looking at images downloaded from google maps, categorize which part of the image depicts the land and which part depicts the sea.
I am a bit of a newbie to computer vision and machine learning so I am looking for a few pointers on specific techniques or API's that may be useful (I am not looking for the code to this solution).
What I have some up with so far:
Edge detection may not be much help (on its own). Although it gives quite a nice outline of the coast, artefacts on the surface/above the sea may give false positives for land mass (stuff like clouds, ships, etc).
Extracting the blue colour element of an image may give a very good indication of which is sea or not (as obviously, the sea has a much higher level of blue saturation than the land)
Any help is of course, greatly appreciated.
EDIT (for anyone who may want to do something similar):
Use the static google maps API to
fetch map images (not satellite
photos, these have too much
noise/artefacts to be precise).
Example url-
http://maps.google.com/maps/api/staticmap?sensor=false&size=1000x1000¢er=dover&zoom=12&style=feature:all|element:labels|visibility:off&style=feature:road|element:all|visibility:off
To generate my threshold images I used the Image processing lab. I would apply the normalized RGB -> extract blue channel filter and then apply Binarization -> otsu threshold. This has produced extremley useful images without the need to fiddle with thresholds values (the algorithm is very clever so I won't muddy the waters and attempt to explain it)
| 0 | 0 | 0 | 1 | 0 | 0 |
I have some trouble on setting of n-linear equations in matlab.I don't know how can I declare in matlab.I need matlab code for setting of n-linear equations..
| 0 | 0 | 0 | 0 | 1 | 0 |
I want to find all coefficients of polynomial expression using multinomial theorem. For eg. coefficients of (a+b+c+d+e)^9.
At this wikipedia link, Multinomial coefficients is given as follows:
But i dont understand how can i get the values of all the coefficients?
I know that for a binomial expression((a+b)^4) -> pascal's triangle is used to find coefficients,
for a trinomial expression ((a+b+c)^5) -> pascal's pyramid is used to find coefficients. But how to find coefficients of a polynomial expression?
Thanks a lot for help
Regards
| 0 | 0 | 0 | 0 | 1 | 0 |
I'd like to know if there is out there some tutorial or guide to understand and implement a Triangle-Triangle intersection test in a 3D Environment. (i don't need to know precise where the intersection happened, but only that an intersection has occurred)
I was going to implement it following a theoric pdf, but i'm pretty stuck at the
Compute plane equation of triangle 2.
Reject as trivial if all points of triangle 1 are on same side.
Compute plane equation of triangle 1.
Reject as trivial if all points of triangle 2 are on same side.
Compute intersection line and project onto largest axis.
Compute the intervals for each triangle.
Intersect the intervals.
point 5 of this guide. I don't really know what's asking (all 5,6 and 7). XD
As i don't have high knowledge in mathematics (well, i know as far the couple of exams at the university has given me (i'm a raw programmer XD)), please try to be as simple as possible with me. :D (I tried to search on google, but most of the links point to some 4-5 pages full of formulas I don't really care to know and I don't understand.)
Thanks for the help
| 0 | 0 | 0 | 0 | 1 | 0 |
I have 160 bits of random data.
Just for fun, I want to generate an English pseudo-poem to "store" this information in. I want to be able to recover this information from the poem. ("Poem" here is a vague term for any kind of poetry.)
Note: This is not a security question, I don't care if someone else will be able to recover the information or even detect that it is there or not.
Criteria for a better poem:
Better aestetics
Better rhyme and foot
Uniqueness
Shorter length
I'd say that the acceptable poem is no longer than three stanzas of four lines each. (But the other, established forms of poetry, like sonnets are good as well.)
I like this idea, but, I'm afraid, that I'm completely clueless in how to do English computer-generated poetry. (I programmed that for Russian when I was young, but looks like that experience will not help me here.)
So, any clues?
Note: I already asked a similar question. I want to try both approaches. Note how good poem criteria are different from the good phrase in parallel question. Remember, this is "just for fun".
Also, I have to note this: There is an RFC 1605 on somewhat related matters. But it do not suggest any implementation details, so it is not quite useful for me, sorry. <g>
| 0 | 1 | 0 | 0 | 0 | 0 |
All I need is to check, using python, if a string is a valid math expression or not.
For simplicity let's say I just need + - * / operators (+ - as unary too) with numbers and nested parenthesis. I add also simple variable names for completeness.
So I can test this way:
test("-3 * (2 + 1)") #valid
test("-3 * ") #NOT valid
test("v1 + v2") #valid
test("v2 - 2v") #NOT valid ("2v" not a valid variable name)
I tried pyparsing but just trying the example: "simple algebraic expression parser, that performs +,-,*,/ and ^ arithmetic operations" I get passed invalid code and also trying to fix it I always get wrong syntaxes being parsed without raising Exceptions
just try:
>>>test('9', 9)
9 qwerty = 9.0 ['9'] => ['9']
>>>test('9 qwerty', 9)
9 qwerty = 9.0 ['9'] => ['9']
both test pass... o_O
Any advice?
| 0 | 0 | 0 | 0 | 1 | 0 |
Background
Create a probability lexicon based on a CSV file of words and tallies. This is a prelude to a text segmentation problem, not a homework problem.
Problem
Given a CSV file with the following words and tallies:
aardvark,10
aardwolf,9
armadillo,9
platypus,5
zebra,1
Create a file with probabilities relative to the largest tally in the file:
aardvark,1
aardwolf,0.9
armadillo,0.9
platypus,0.5
zebra,0.1
Where, for example, aardvark,1 is calculated as aardvark,10/10 and platypus,0.5 is calculated as platypus,5/10.
Question
What is the most efficient way to implement a shell script to create the file of relative probabilities?
Constraints
Neither the words nor the numbers are in any order.
No major programming language (such as Perl, Ruby, Python, Java, C, Fortran, or Cobol).
Standard Unix tools such as awk, sed, or sort are welcome.
All probabilities must be relative to the highest probability in the file.
The words are unique, the numbers are not.
The tallies are natural numbers.
Thank you!
| 0 | 0 | 0 | 0 | 1 | 0 |
I want to parse a text and categorize the sentences according to their grammatical structure, but I have a very small understanding of NLP so I don't even know where to start.
As far as I have read, I need to parse the text and find out (or tag?) the part-of-speech of every word. Then I search for the verb clause or whatever other defining characteristic I want to use to categorize the sentences.
What I don't know is if there is already some method to do this more easily or if I need to define the grammar rules separately or what.
Any resources on NLP that discuss this would be great. Program examples are welcome as well. I have used NLTK before, but not extensively. Other parsers or languages are OK too!
| 0 | 1 | 0 | 0 | 0 | 0 |
Can you help me in providing a prototype to detect illicit content in images, using python.
| 0 | 1 | 0 | 0 | 0 | 0 |
I´m reviewing a code from Toronto perceptron MATLAB code
The code is
function [w] = perceptron(X,Y,w_init)
w = w_init;
for iteration = 1 : 100 %<- in practice, use some stopping criterion!
for ii = 1 : size(X,2) %cycle through training set
if sign(w'*X(:,ii)) ~= Y(ii) %wrong decision?
w = w + X(:,ii) * Y(ii); %then add (or subtract) this point to w
end
end
sum(sign(w'*X)~=Y)/size(X,2) %show misclassification rate
end
So I was reading how to apply this function to data matrix X, and target Y, but, do not know how to use this function, I understand, it returns a vector of weights, so it can classify.
Could you please give an example, and explain it??
I´ve tried
X=[0 0; 0 1; 1 1]
Y=[1 0; 2 1]
w=[1 1 1]
Result = perceptron( X, Y, w )
??? Error using ==> mtimes
Inner matrix dimensions must agree.
Error in ==> perceptron at 15
if sign(w'*X(:,ii)) ~= Y(ii)
Result = perceptron( X, Y, w' )
??? Error using ==> ne
Matrix dimensions must agree.
Error in ==> perceptron at 19
sum(sign(w'*X)~=Y) / size(X,2);
Thanks
Thank you for the anwers, I got one more, If I change the Y = [0, 1], what happens to the algorithm?.
So, Any input data will not work with Y = [0,1] with this code of the perceptron right?,
-----------------------------EDIT------------------------
One more question, if I want to plot the line that divides the 2 classes, I know we can get that the line solving linear equation system that has to do with weights, but how,
what could I do?, I'm trying something like
% the initial weights
w_init = [ 1 1 1]';
% the weights returned from perceptron
wtag = perceptron(X,Y,w_init,15);
% concatenate both
Line = [wtag,w_init]
% solve the linear system, am I correct doing this?
rref(Line')
% plot???
| 0 | 1 | 0 | 0 | 0 | 0 |
Shouldn't it return a DRAW?
def alphabeta(alpha, beta, player)
best_score = -INFINITY
if not self.has_available_moves?
return DRAW
elsif self.has_this_player_won?(player) == player
return WIN
elsif self.has_this_player_won?(1 - player) == 1 - player
return LOSS
else
self.remaining_moves.each do |move|
if alpha >= beta then return alpha end
self.make_move_with_index(move, player)
move_score = -alphabeta(-beta, -alpha, 1 - player)
self.undo_move(move)
if move_score > alpha
alpha = move_score
next_move = move
end
best_score = alpha
end
end
return best_score
end
constants:
WIN = 1
LOSS = -1
DRAW = 0
INFINITY = 100
COMPUTER = 0
HUMAN = 1
test case:
# computer is 0, human is 1
# c h c
# _ h h
# _ c h -- computer's turn
test "make sure alpha-beta pruning works (human went first) 1" do
@board.state = [0,1,0,nil,1,1,nil,0,1]
score = @board.alphabeta(100, -100, Board::COMPUTER)
assert_equal(Board::DRAW, score)
end
relevant methods and other things to help read the code above:
self.state = Array.new(9)
WAYS_TO_WIN = [[0, 1, 2], [3, 4, 5], [6, 7, 8], [0, 3, 6], [1, 4, 7], [2, 5, 8],[0, 4, 8], [2, 4, 6]]
def make_move_with_index(index, player)
self.state[index] = player
end
def undo_move(index)
self.state[index] = nil
end
def has_this_player_won?(player)
WAYS_TO_WIN.each do |way_to_win|
return true if self.state.values_at(*way_to_win).uniq.size == 1 and self.state[way_to_win[0]] == player
end
return false
end
def remaining_moves
self.state.each_with_index.map{|e,i| (e.nil?) ? i : nil }.compact
end
def has_available_moves?
return self.state.include? nil
end
| 0 | 1 | 0 | 0 | 0 | 0 |
I have two integers (amount of bytes of two files). One is always smaller if not the same than the other. I want to calculate the percentage that the smaller is of the bigger.
I'm using plain C. I've applied the math formula, but am getting always 0:
printf("%d\r", (current/total)*100);
Any ideas?
| 0 | 0 | 0 | 0 | 1 | 0 |
... It's not as silly as it sounds...
I have the following code, which is used by my ajax table script to display database stuff on the page in a table.
foreach($ct->data as $key => $value){
$ct->data[$key][2]='<a href="quantity.php?partno='.$ct->data[$key][0].'&description='.$ct->data[$key][1].'&quantity='.$ct->data[$key][2].'&order='.$o.'">'.$ct->data[$key][2].'</a>';
$ct->data[$key][3]='<a href="quantity.php?partno='.$ct->data[$key][0].'&description='.$ct->data[$key][1].'&price='.$ct->data[$key][3].'&order='.$o.'">'.$ct->data[$key][3].'</a>';
if($ct->data[$key][4] == "" || $ct->data[$key][4] == null)
$ct->data[$key][4]='<a href="freight.php?partno='.$ct->data[$key][0].'&description='.$ct->data[$key][1].'&freight='.$ct->data[$key][4].'&order='.$o.'">Edit Charge.</a>';
else
$ct->data[$key][4]='<a href="freight.php?partno='.$ct->data[$key][0].'&description='.$ct->data[$key][1].'&freight='.$ct->data[$key][4].'&order='.$o.'">'.$ct->data[$key][4].'</a>';
$Total =$Total+ $ct->data[$key][3];
$freight =$freight+ $ct->data[$key][4];
}
And as you can see, in the foreach loop, I am trying to add up the contents of 2 columns.
The $Total column or, $ct->data[$key][3] lists the Prices for each row of products, and the $freight column does the same for each row of Freight charges.
And inside the foreach loop, I am trying to add together the total amount of prices, and Freight charges.
I'm not sure if I'm doing it the right way, because when I check the database, it just adds '0' (without the quotes). So it's not adding up!
For example, if there are a total of 3 rows in the table, and each product is 1 (dollar), it should add up to 3, right? And same goes for the $freight ones.
Can someone please tell me what I'm doing wrong here?
| 0 | 0 | 0 | 0 | 1 | 0 |
Using openGL (just 2d), I'm trying to rotate a texture so it's pointing towards a point on screen. I'll show an image first to help me explain.
http://img692.imageshack.us/img692/3088/probe.png
Say my texture is the blue dot at point 1 and it is moving to its destination at point 2. I want to rotate #1 so that it is "pointing" towards point 2 (the texture is a bird so it has a defined "front"). To do this, I need to find out angle 3. Similarly, if my bird is at point #4 travelling towards point 5, I need to work out angle 6.
What's the secret to doing this?
| 0 | 0 | 0 | 0 | 1 | 0 |
I need to find a maximum of the function:
a1^x1 * const1 + a2^x2 * const2 +....+ ak^xk * constk = qaulity
where xk>0 and xk is integer. ak is constant.
constraint:
a1^x1 * const1*func(x1) + a2^x2 * const2*func(x2) +....+ ak^xk * constk*func(xk) < Budget
Where func is a discrete function:
func(x)
{
switch(x)
{
case 1: return 423;
case 2: return 544;
...
etc
}
}
k may be big(over 1000). x less then 100.
What is the best method?
| 0 | 0 | 0 | 0 | 1 | 0 |
I have a database with 2.000.000 messages. When an user receipt a message I need find relevant messages in my database based in occurrence of words.
I had tried run a batch process to summarize my database:
1 - Store all words(except an, a, the, of, for...) of all messages.
2 - Create association between all messages and the words contained therein (I also store the frequence of this word appears in the message.)
Then, when I receipt a message:
1 - I parse words (it looks like with the first step of my batch process.)
2 - Perform query in database to fetching messages sorted by numbers of coincident words.
However, the process of updating my words base and the query to fetching similar messages are very heavy and slow. The word base update lasts ~1.2111 seconds for a message of 3000 bytes. The query similar messages lasts ~9.8 seconds for a message with same size.
The database tuning already been done and the code works fine.
I need a better algorithm to do it.
Any ideas?
| 0 | 1 | 0 | 0 | 0 | 0 |
This question is related to 873448.
From Wikipedia:
The Blue Brain Project is an attempt to create a synthetic brain by reverse-engineering the mammalian brain down to the molecular level. [...] Using a Blue Gene supercomputer running Michael Hines's NEURON software, the simulation does not consist simply of an artificial neural network, but involves a biologically realistic model of neurons.
"If we build it correctly it should speak and have an intelligence and behave very much as a human does."
My question is how the software works internally. If it "involves a biologically realistic model of neurons", how is that different from a neural network, and why can't neural networks simulate a biological brain well while this project would be able to? And, how is NEURON software used in the simulation?
Lastly, I apologize if this question doesn't belong here (maybe the BioStar StackExchance would be a better place to ask).
| 0 | 1 | 0 | 0 | 0 | 0 |
Working in C++, I'd like to find the sum of some quantities, and then take the log of the sum:
log(a_1 + a_2 + a_3 + ... + a_n)
However, I do not have the quantities themselves, I only have their log'd values:
l_1 = log(a_1), l_2 = log(a_2), ... , l_n = log(a_n)
Is there any efficient way to get the log the sum of the a_i's? I'd like to avoid
log(s) = log(exp(l_1) + exp(l_2) + ... + exp(l_n))
if possible - exp becomes a bottleneck as the calculation is done many times.
| 0 | 0 | 0 | 0 | 1 | 0 |
I need to find an algorithm which determines a relationship between a square and rectangle. It must be able to determine if:
The square is completely inside the rectangle
The square is partially inside (overlaps) the rectangle
Square's corner only touches a rectangle's corner
Square's edge is on the rectangle's edge
And here are the inputs (given values) that will help us to extract a mathematical formula for each case:
x coordinate of the center of the square = squareX
y coordinate of the center of the square = squareY
width of the square = squareW
x coordinate of the center of the rectangle = recX
y coordinate of the center of the rectangle = recY
width of the rectangle = recW
length of the rectangle = recL
P.S: Rectangle's sizes are always bigger than the square's width.
I will write the code in Java once we can extract an algorithm using mathematical operations.
Edit:
For the case of corners in touch, here is the code I wrote, and it works (Math.abs means the absolute value):
((Math.abs(Math.abs(recX-squareX)-(recW+squareW)/2))<=0.001) && ((Math.abs(Math.abs(recY-squareY)-(recL+squareW)/2))<=0.001)
| 0 | 0 | 0 | 0 | 1 | 0 |
I would like to ask something about the implementation of Intelligent Product Recommendation
As I need to build an online shopping system using JSP and Mysql, I want to implement a function,
which can automatically recommend some related products when the user checks for one product details.
However, I did not have any learning experience for Artificial Intelligence.
There are too many resources on the Internet but I don't know which are good for learning.
Therefore, would anyone suggest some useful websites for studying such type of programming skill(that is, AI).
Thanks very much!
| 0 | 1 | 0 | 0 | 0 | 0 |
I am using R tool to calculate SVD (svd(m)) and it works on small matrix but as I pass it 20Kx20X matrix. After processing, it gives the following error
Error in svd(m) : infinite or missing values in 'x'
I checked and there is no row or column with all 0 values and no duplicate in row and
column. All columns have values.
I cannot past 20Kx20K matrix here :(
| 0 | 0 | 0 | 0 | 1 | 0 |
i'm attempting to populate an array with random numbers, but the random numbers must be a certain, minimum distance apart from each other.
i've populated an array with 5 random numbers between 0 - 100:
private var myArray:Array = new Array();
for (var i:uint = 0; i < 5; i++)
myArray.push(Math.round(Math.random() * 100));
next i've sorted the array in numeric order:
myArray.sort(Array.NUMERIC);
after populating and sorting let's assume that myArray now contains these values:
26, 27, 42, 92, 97
now i would like some ore all of the array values to be reset, if they need to be, so that they are at least a certain percentage (let's say 10%) of the maximum value (100) apart from each other.
the first 2 values (26 and 27) are not at least 10% apart and neither are the last 2 values (92 and 97). however, if i simply moved the value 27 10% away from 26, so that 27 changes to 37, 37 now conflicts with the next value of 42.
what is the best approach for populating an array of random numbers who's values will be at least a certain percentage apart from one another but still random.
it may go without saying, but i'm looking for a solution that is portable, where maximum values and minimum distribution percentages can be anything, not just for my example above.
| 0 | 0 | 0 | 0 | 1 | 0 |
We currently use ILOG BRMS for .NET to allow business users to create logic in our system without knowing how to program. This rule is created by a business user (ie: It's a part of the system, not a part of the specification) :
definitions
set 'the letter event' to the scheduled DelinquentLetterEvent on the invoice;
set 'final notice possibility1' to the bill date of the invoice + 36 days;
set 'final notice possibility2' to the time of 'the letter event' + 7 days;
set 'final notice result' to the most future date from these values {
'final notice possibility1', 'final notice possibility2' };
then
in the event that 'final notice result' is not a mailing date,
change it to the next available mailing date;
add a new FinalNoticeEvent scheduled for 'final notice result' to the invoice;
The system performs the equivalent in .Net (here showing psuedo C#):
//variable declarations
ScheduledEvent theLetterEvent = theInvoice.GetScheduledEvent(
KnownEventType.DelinquentLetterEvent);
DateTime noticePossibility1 = theInvoice.BillDate.AddDays(36);
DateTime noticePossibility2 = theLetterEvent.Time.AddDays(7);
DateTime[] possibilities = new DateTime[]()
{ noticePossibility1, noticePossibility2 };
DateTime noticeResult = CustomClass.Max(possibilities);
//actions
CustomClass2.MakeNextMailingDate(ref noticeResult);
theInvoice.AddScheduledEvent(KnownEventType.FinalNoticeEvent, noticeResult);
Programmers specify at design time what text is used for each class/method/property. For example, the text for that last method is:
add a new {0} scheduled for {1} to {this}
It's slowly dawning on me that I don't need a BRMS at all. The concept of matching of rules to asserted instances is just as alien to business users as it is to programmers. Our business users are somewhat familiar with SQL scripting (and some know a bit of VBA), so they are comfortable with sequential execution.
What I really want is a way to specify text at design time (a DSL) that maps to classes/methods/properties for natural language programming, preferably outside of a BRMS.
Does such a thing exist? What is the proper name for this concept?
Responses:
We have considered scripting languages to fill this need broadly. In specific, they do not offer the text substitution/mapping to .NET code that I seek.
I want to write a c# method, then declare some sensible phrases by which one might invoke it.
ANTLR - thanks for the tip. This is a generic parser. I will no doubt require a parser if I want to implement this myself.
Any artificial language you invent with a stilted vocabulary focused in a problem area is by definition a "domain specific langauge".
I feel this statement is as good as an answer as I can get to my questions. Thanks.
If you need fully general computation, you're going to end up with a typical computer language. If you can narrow the scope a lot, you might end with something useful.
I can narrow the scope all the way down to calling the methods I've implemented, but the catch is that as I add more methods, I want to attach more vocabulary for those new methods.
The DSL will evolve whether we continue to use ILOG or something else as the supporting infrastructure for the language.
| 0 | 1 | 0 | 0 | 0 | 0 |
I was thinking (oh god, it starts badly) about neuron networks and how it is not possible to simulate those because they require many atomic operation at the same time (here meaning simultaneously), because that's how neurons are faster: they are many to compute stuff.
Since our processors are 32 bits so they can compute a significantly larger band (meaning a lot of different atomic numbers, being floating points or integers), the frequency race is also over and manufacturers start shipping multicore processors, requiring developpers to implement multithreading in their application.
I was also thinking about the most important difference between computers and brains; brains use a lot of neurons, while computers use precision at a high frequency: that's why it seems harder or impossible to simulate an real time AI with the current processor model.
Since 32bits/64bits chips also take a great deal of transistors and since AI doesn't require vector/floating point precision, would it be a good idea to have many more 8bits cores on a single processor, like 100 or 1000 for example since they take much less room (I don't work at intel or AMD so I don't know how they design their processors, it's just a wild guess), to plan for those kind of AI simulations ?
I don't think it would only serve AI research though, because I don't know how webservers can really take advantage of 64 bits processors (strings use 8bits), Xeon processors are only different considering their cache size.
| 0 | 1 | 0 | 0 | 0 | 0 |
Hey, I'm using pyGame and I want to:
A) make a function that returns the angle between two points. I've tried doing this with math.atan2 and I'm getting really wierd returns. I tried this with both (delta X, deltaY) and (deltaY, deltaX). Any suggestions?
B) given a length and an angle, return a point using those two from 0.
For example, LengthDir(2,45) using (length,angle) would return (2,2).
Thanks for the help. I've searched all over the internet and I couldn't find anything to help me...
| 0 | 0 | 0 | 0 | 1 | 0 |
I was wondering if I should invest my time in learning AI using Prolog. The decision is simple. If it will have any kind of benefit in my career as an iPhone developer, I would do so. Otherwise, I'll skip it.
So, is there any benefit in learning AI using Prolog for an iPhone developer? (especially for building games)
And, if so, how???
Thanks!
| 0 | 1 | 0 | 0 | 0 | 0 |
//This program evaluates an expression of two fractions added or subtracted
#include <iostream>
#include <cmath>
using namespace std;
int CrossMultiplication(int, char, int);
int DenominatorConversion(int, int);
int main(){
int NumeratorA;
int NumeratorB;
int DenominatorA;
int DenominatorB;
char Operation;
char Slash;
Slash = '/';
cout << "This program evaluates an expression of two fractions added or subtracted.
";
cout << "The expression should look like this: A/B + C/D where A, B, C, and D are ";
cout << "integers, the + sign can be a - sign and spacing is not important.
";
cout << "
Enter the expression: ";
cin >> NumeratorA >> Slash >> DenominatorA >> Operation >> NumeratorB >> Slash >> DenominatorB;
cout << NumeratorA << Slash << DenominatorA << " " << Operation << " " << NumeratorB << Slash << DenominatorB << " " << "=" << " " << CrossMultiplication(NumeratorA,Operation,NumeratorB) << Slash << DenominatorConversion(DenominatorA,DenominatorB);
cout << "
Thanks for using this program.";
cin.get();
cin.get();
return 0;
}
int CrossMultiplication (int NumeratorA,char Operation, int NumeratorB){
int NewNumerator;
int DenominatorA;
int DenominatorB;
switch (Operation) {
case '+': NewNumerator = NumeratorA*DenominatorB + NumeratorB*DenominatorA;
break;
case '-':NewNumerator = NumeratorA*DenominatorB - NumeratorB*DenominatorA;
break;
return NewNumerator;
}
}
int DenominatorConversion(int DenominatorA, int DenominatorB){
int NewDenominator;
NewDenominator = DenominatorA*DenominatorB;
return NewDenominator;
}
| 0 | 0 | 0 | 0 | 1 | 0 |
Possible Duplicate:
Fastest way to list all primes below N in python
Although I already have written a function to find all primes under n (primes(10) -> [2, 3, 5, 7]), I am struggling to find a quick way to find the first n primes. What is the fastest way to do this?
| 0 | 0 | 0 | 0 | 1 | 0 |
I'm looking for a simple algorithm that, given a rectangle with width w and height h, splits the rectangle into n more or less equal sized and shape rectangles and calculates the center of these rectangles.
EDIT: Forgot to mention that the shapes should be as similar as possible to a square.
Any hints how to start?
| 0 | 0 | 0 | 0 | 1 | 0 |
If you're familiar with any fantasy sports draft, the draft-order grid looks something like this:
EXAMPLE 1 (3-teams):
Round Team 1 Team 2 Team 3
1 1 (1.1) 2 (1.2) 3 (1.3)
2 6 (2.3) 5 (2.2) 4 (2.1)
3 7 (3.1) 8 (3.2) 9 (3.3)
The numbers 1-9 represent the overall pick number of the draft.
The items in parentheses represent the round_number and pick_number_of_that_round.
I cannot figure out a formula which converts my overall_pick_number into it's proper pick_number_of_that_round.
In the above example, the number 8 equals 2 (the 2nd pick of the 3rd round). But in a 4-team league, the number 8 equals 4 (the 4th pick of the 2nd round).
EXAMPLE 2 (4-teams):
Round Team 1 Team 2 Team 3 Team 4
1 1 (1.1) 2 (1.2) 3 (1.3) 4 (1.4)
2 8 (2.4) 7 (2.3) 6 (2.2) 5 (2.1)
3 9 (3.1) 10 (3.2) 11 (3.3) 12 (3.4)
I thought about trying to dynamically build an associative array based on the number of teams in the league containing every pick and which pick it belonged to, but it's just beyond me.
| 0 | 0 | 0 | 0 | 1 | 0 |
I want to decompose the number into the product of the largest square in this number and some other number, but I am stuck at some point. I would really appreciate some suggestions. This is what I've done so far:
I take the number on the input, factorize into prime numbers, and put the sequence of prime numbers to ArrayList. Numbers are sorted, in a sense, thus the numbers in the sequence are increasing.
For example,
996 is 2 2 3 83
1000 is 2 2 2 5 5 5
100000 is 2 2 2 2 2 5 5 5 5 5
My idea now is to count number of occurrences of each elements in the sequence, so if the number of occurrences is divisible by two, then this is the square.
In this way, I can get another sequence, where the right most element divisible by two is the largest square.
What is the most efficient way to count occurrences in the ArrayList? Or is there any better way to find the largest square?
| 0 | 0 | 0 | 0 | 1 | 0 |
According to the book I'm reading, interpolation search takes O(loglogn) in average case.
The book assumes that each compare reduce the length of the list from n to sqrt(n). Well, it isn't difficult to work out the O(loglogn) given this assumption.
However, the book didn't talk more about this assumption except that it says this is correct.
Question: can anyone give some explanation on why this is true?
| 0 | 0 | 0 | 0 | 1 | 0 |
I'm having trouble with the iTunes XML duration column. I'm trying to figure out exactly what this integer is so I can accurately determine the minutes and seconds duration of an mp3.
The integer for a specific MP3 in a field labeled "Total Time" is 2005812. The MP3 is actually 33:26 according to iTunes. Any ideas on what format this is? How should I go about figuring this out?
I found some documentation online to say to do something like this:
$minutes = bcmod(($sermon['duration'] / 60), 60);
$seconds = bcmod($sermon['duration'], 60);
The problem is that it comes out being about 10 minutes long, which isn't accurate.
| 0 | 0 | 0 | 0 | 1 | 0 |
Please help. I've been working on this non stop and can't get it right. The issue I'm having is that the output I'm getting for the inverse is always 1.
This is the code that I have (it computes GCD and trying to modify so it also computes a^-1):
import java.util.Scanner;
public class scratchwork
{
public static void main (String[] args)
{
Scanner keyboard = new Scanner(System.in);
long n, a, on, oa;
long gcd = 0;
System.out.println("Please enter your dividend:");
n= keyboard.nextLong();
System.out.println("Please enter your divisor:");
a= keyboard.nextLong();
on= n;
oa= a;
while (a!= 0)
{gcd=a;
a= n% a;
n= gcd;
}
System.out.println("Results: GCD(" + odd + ", " + odr + ") = " + gcd);
long vX; vS; vT; vY; q; vR; vZ; m; b;
vX = n; vY=a;
vS = 0; vT = 1; m=0; b=0;
while (a != 0)
{
m=vT;;
b=vX;
q = n / a;
vR = vS - q*vT;
tZ = n - q*a;
vS = vT; n = da;
vT = tY; dY = vZ;
}
if (d>1) System.out.println("Inverse does not exist.");
else System.out.println("The inverse of "+oa+" mod "+on+" is "+vT);
}
}
| 0 | 0 | 0 | 0 | 1 | 0 |
I'm given the task of determining whether an advertisement is suited for male or female.
What's the best way of determining this?
The words looks like this:
Cheetos
Coca Cola
Nike
Ferrari
24
Arrested Development
Transformers
Nestle
American Eagle
For each word, I'd like to know if it's more associated to male or female. It doesn't have to be correct. I know it's hard to tell if "nike" is suited towards male or female. Just any methodology would help me brainstorm.
| 0 | 1 | 0 | 0 | 0 | 0 |
after running the perceptron code in Matlab I get the following weights:
result=
2.5799
2.8557
4.4244
-4.3156
1.6835
-4.0208
26.5955
-12.5730
11.5000
If i started with these weights :
w = [ 1 1 1 1 1 1 1 1 1]';
How do I plot the line that separates the 2 classes.
Is necessary to solve a linear system, but how?
Line = [result,w]
% solve the linear system, am I correct doing this?
rref(Line')
Is it correct the way to calculate the values, that will be use to plot?
How to plot the line??
any example???
| 0 | 1 | 0 | 0 | 0 | 0 |
In my exam, i was supposed to write all pumping lemma conditions. that exactly what i did :
a friend told me that there is some errors but i can't find them...
Can some one help please ? what are the errors & why ?
| 0 | 0 | 0 | 0 | 1 | 0 |
I'm basically looking for a summation function that will compute multinomials given the number of variables and a degree.
Example
2 Variables; 2 Degrees:
x^2+y^2+x*y+x+y+1
Thanks.
| 0 | 0 | 0 | 0 | 1 | 0 |
I know this is not a mathematical forum but given the bright minds that participate here, i am sure that this question is of interest nevertheless. How would you develop and explain the following statement:
"we can convert the product of a set
of primes into a sum of the logarithms
of the primes by applying logarithms
to both parts of this conjecture"
| 0 | 0 | 0 | 0 | 1 | 0 |
How do you use money in visual basic I know that I have to set nickels and divide by 5 and I am suppose to have another expression to the number. Then i am suppose to determine what change i would have left so that way i can determine how many pennies I have. Thanks to all who looks.
Dim change As Integer
Dim amountused As Integer
Dim quarters As Integer
Dim dimes As Integer
Dim nickels As Integer
Dim pennies As Integer
Console.WriteLine("Please enter your amount here")
amountused = Console.ReadLine()
Console.WriteLine("change= 100-amount used")
Console.WriteLine(quarters = change \ 25)
Console.WriteLine(dimes = (change - quarters * 25) / 10)
Console.WriteLine(nickels = change \ 5)
Console.WriteLine(pennies =
edit:Can someone hint to me what I am doing wrong I don't get nothing for output Thanks... The hint could be example check this line. Thanks
Dim change As Integer
Dim amountused As Integer
Dim quarters As Integer
Dim dimes As Integer
Dim nickels As Integer
Dim pennies As Integer
Console.WriteLine("Please enter your amount here")
amountused = Console.ReadLine()
change = ("100 - amountused")
quarters = change \ 25
Console.WriteLine("Quarters:{0}", quarters)
change = change - (quarters * 25)
dimes = change \ 10
Console.WriteLine("Dimes: {0}", quarters)
change = change - (dimes * 10)
nickels = change \ 5
change = change - (nickels * 5)
Console.WriteLine("nickels: {0}", quarters)
change = pennies \ 1
change = change - (pennies * 1)
Console.WriteLine("pennies:{0}", pennies)
| 0 | 0 | 0 | 0 | 1 | 0 |
I'm using the C4.5 algorithm (can be found here)
My names are here:
Play, Don't Play.
Sky: Sunny, Cloudy, Rainy.
AirTemp: Warm, Cold.
Humidity: Normal, High.
Wind: Strong, Weak.
Water: Warm, Cool.
Forecast: Same, Change.
And my data is here
Sunny, Warm, Normal, Strong, Warm, Same, Play
Sunny, Warm, High, Strong, Warm, Same, Play
Sunny, Warm, High, Strong, Cool, Change, Play
Rainy, Cold, High, Strong, Warm, Change, Don't Play
The output I get from the algorithm which I run with the command
c4.5.exe -f v2 -v 1 > v2.r3
is
C4.5 [release 8] decision tree generator Tue Jan 18 16:41:25 2011
----------------------------------------
Options:
File stem <v2>
Verbosity level 1
Read 4 cases (6 attributes) from v2.data
4 items, total weight 4.0
best attribute Forecast inf 1.000 gain 0.311 val 0.311
Collapse tree for 4 items to leaf Play
Decision Tree:
Play (4.0/1.0)
Play (4.00:1.00/2.19)
Tree saved
Evaluation on training data (4 items):
Before Pruning After Pruning
---------------- ---------------------------
Size Errors Size Errors Estimate
1 1(25.0%) 1 1(25.0%) (54.7%) <<
My problem is that the tree is based on the feature forecast changed into a single node. I followed the pseudo code for the algorithm myself and I always end up with a tree that uses the feature Sky to decide whether to play or not. What am I doing wrong?
I think my problem is because I can't set the pruning confidence level. I've tried it but it won't accept my input, e.g.
c4.5.exe -f v2 -v 1 -c 0.5 > v2.r3
or
c4.5.exe -f v2 -v 1 -c 50% > v2.r3
doesn't work.
| 0 | 0 | 0 | 1 | 0 | 0 |
A friend of mine sent me this question. I haven't really been able to come up with any kind of algorithm to solve this problem.
You are provided with a no. say 123456789 and two operators * and +. Now without changing the sequence of the provided no. and using these operators as many times as you wish, evaluate the given value:
eg: given value 2097
Solution: 1+2+345*6+7+8+9
Any ideas on how to approach problems like these?
| 0 | 0 | 0 | 0 | 1 | 0 |
My project is a directional antenna which is mounted on a self-stabilizing base. The language I wish to use is python, but changing this to a more suited language, is a possibility, if needed.
Problem 1:
How would you go about taking in serial data in real-time[1], and then parse the data in python?
Problem 2:
How can I then send the output of the program to servos, which are mounted on the base? (feedback system).
[1](Fastest possible time for data transfer, processing and then output)
| 0 | 0 | 0 | 0 | 1 | 0 |
How does the system perform the 2^56 modulo 7, if it's 32 bits operating system in cryptography for example?
And how it stored in memory?
| 0 | 0 | 0 | 0 | 1 | 0 |
So I have a 8x8 square. There is a line in it.
Line size == 8 angle == 0.
One of line points is always on one of the top corners.
What would be a formula to retrieve points coordinates where line crosses borders of square? (positive angle means one of line points is 0, 0. negative 0, 8 )
What would be math formula for each of coordinates points? (in pseudo code if possible)
| 0 | 0 | 0 | 0 | 1 | 0 |
Greetings. I'm trying to approximate the function
Log10[x^k0 + k1], where .21 < k0 < 21, 0 < k1 < ~2000, and x is integer < 2^14.
k0 & k1 are constant. For practical purposes, you can assume k0 = 2.12, k1 = 2660. The desired accuracy is 5*10^-4 relative error.
This function is virtually identical to Log[x], except near 0, where it differs a lot.
I already have came up with a SIMD implementation that is ~1.15x faster than a simple lookup table, but would like to improve it if possible, which I think is very hard due to lack of efficient instructions.
My SIMD implementation uses 16bit fixed point arithmetic to evaluate a 3rd degree polynomial (I use least squares fit). The polynomial uses different coefficients for different input ranges. There are 8 ranges, and range i spans (64)2^i to (64)2^(i + 1).
The rational behind this is the derivatives of Log[x] drop rapidly with x, meaning a polynomial will fit it more accurately since polynomials are an exact fit for functions that have a derivative of 0 beyond a certain order.
SIMD table lookups are done very efficiently with a single _mm_shuffle_epi8(). I use SSE's float to int conversion to get the exponent and significand used for the fixed point approximation. I also software pipelined the loop to get ~1.25x speedup, so further code optimizations are probably unlikely.
What I'm asking is if there's a more efficient approximation at a higher level?
For example:
Can this function be decomposed into functions with a limited domain like
log2((2^x) * significand) = x + log2(significand)
hence eliminating the need to deal with different ranges (table lookups). The main problem I think is adding the k1 term kills all those nice log properties that we know and love, making it not possible. Or is it?
Iterative method? don't think so because the Newton method for log[x] is already a complicated expression
Exploiting locality of neighboring pixels? - if the range of the 8 inputs fall in the same approximation range, then I can look up a single coefficient, instead of looking up separate coefficients for each element. Thus, I can use this as a fast common case, and use a slower, general code path when it isn't. But for my data, the range needs to be ~2000 before this property hold 70% of the time, which doesn't seem to make this method competitive.
Please, give me some opinion, especially if you're an applied mathematician, even if you say it can't be done. Thanks.
| 0 | 0 | 0 | 0 | 1 | 0 |
Thanks in advance for any help...
I'm trying to (1) generate a begin time and end time for a form, (2) find the difference between the two, and (3) add the difference to a new input.
Here's what I have so far:
<a href="#" id="starttime">Begin time</a>
<input id="starttimeinput" name="starttimeinput" type="text" value="">
<script>
$("#starttime").click(function () {
var begintime = event.timeStamp;
$("#starttimeinput").val(begintime);
});
</script>
<a href="#" id="endtime">end time</a>
<input id="endtimeinput" name="endtimeinput" type="text" value="">
<script>
$("#endtime").click(function () {
var endtime = event.timeStamp;
$("#endtimeinput").val(endtime);
});
</script>
<input id="totaltime" name="totaltime" type="text">
<script>
$("#totaltime").focus(function () {
var begintime = $("#starttimeinput").val();
var endtime = $("#endtimeinput").val();
var totaltime = endtime - begintime;
$("#totaltime").val(totaltime);
});
</script>
The first part works (entering the timestamps into the beginning time and end time inputs). I've never worked with numbers before and can't figure out the second part. The result that comes up is "NaN".
Also this might be useful to know the the time between when the links are clicked should be around 30 seconds...
Thanks much for any help you guys have answered so many questions of mine without me having to post!
| 0 | 0 | 0 | 0 | 1 | 0 |
I understand how k-nearest-neighbours (KNN) works, but I am unfamiliar with the term "soft-voting". What is soft voting in relation to KNN and how does it work compared to standard KNN voting?
A simple example comparing the two voting schemes would be useful and a link to a Matlab implementation would be a nice bonus.
Thanks
Josh
| 0 | 0 | 0 | 1 | 0 | 0 |
Whilst looking for a C++ implementation of Excel's NORMDIST (cumulative)
function I found this on a website:
static double normdist(double x, double mean, double standard_dev)
{
double res;
double x=(x - mean) / standard_dev;
if (x == 0)
{
res=0.5;
}
else
{
double oor2pi = 1/(sqrt(double(2) * 3.14159265358979323846));
double t = 1 / (double(1) + 0.2316419 * fabs(x));
t *= oor2pi * exp(-0.5 * x * x)
* (0.31938153 + t
* (-0.356563782 + t
* (1.781477937 + t
* (-1.821255978 + t * 1.330274429))));
if (x >= 0)
{
res = double(1) - t;
}
else
{
res = t;
}
}
return res;
}
My limited maths knowledge made me think about Taylor series, but I am unable to determine where these numbers come from:
0.2316419,
0.31938153,
-0.356563782,
1.781477937,
-1.821255978,
1.330274429
Can anyone suggest where they come from, and how they can be derived?
| 0 | 0 | 0 | 0 | 1 | 0 |
I have several measures:
Profit and loss (PNL).
Win to loss ratio (W2L).
Avg gain to drawdown ratio (AG2AD).
Max gain to maximum drawdown ratio (MG2MD).
Number of consecutive gains to consecutive losses ratio (NCG2NCL).
If there were only 3 measures (A, B, C), then I could represent the "total" measure as a magnitude of a 3D vector:
R = SQRT(A^2 + B^2 + C^2)
If I want to combine those 5 measures into a single value, would it make sense to represent them as the magnitude of a 5D vector? Is there a way to put more "weight" on certain measures, such as the PNL? Is there a better way to combine them?
Update:
I'm trying to write a function (in C#) that takes in 5 measures and represents them in a linear manner so I can collapse the multidimensional values into a single linear value. The point of this is that it will allow me to only use one variable (save memory) and it will provide a fast method of comparison between two sets of measures. Almost like building a hash value, but each hash can be used for comparison (i.e. >, <, ==).
The statistical significance of the values is the same as the order they're listed: PNL is the most significant while NCG2NCL is the least significant.
| 0 | 1 | 0 | 1 | 0 | 0 |
I have an artificial neural network which plays Tic-Tac-Toe - but it is not complete yet.
What I have yet:
the reward array "R[t]" with integer values for every timestep or move "t" (1=player A wins, 0=draw, -1=player B wins)
The input values are correctly propagated through the network.
the formula for adjusting the weights:
What is missing:
the TD learning: I still need a procedure which "backpropagates" the network's errors using the TD(λ) algorithm.
But I don't really understand this algorithm.
My approach so far ...
The trace decay parameter λ should be "0.1" as distal states should not get that much of the reward.
The learning rate is "0.5" in both layers (input and hidden).
It's a case of delayed reward: The reward remains "0" until the game ends. Then the reward becomes "1" for the first player's win, "-1" for the second player's win or "0" in case of a draw.
My questions:
How and when do you calculate the net's error (TD error)?
How can you implement the "backpropagation" of the error?
How are the weights adjusted using TD(λ)?
Thank you so much in advance :)
| 0 | 1 | 0 | 0 | 0 | 0 |
Greetings and Salutations,
My web application utilizes the EvalMath class found at PHPClasses. Unfortunately, it keeps generating approximately a 100 mb error log file each day because of this undefined offset error within the EvalMath class.
It is erroring on the 385th line or when the following function is called:
function last($n=1) {
return $this->stack[$this->count-$n];
}
I've isolated the issue to when some mathematics expressions are entered:
(x^2)/(x^3+9) [returns two errors offset: -2 and offset: -1]
x^2/(x^3+9) [returns one error offset: -1]
x^2*(x^3-5) [returns one error offset: -1]
So, it appears to be an issue with how the class handles multiplication/division and parenthesis. Any suggestions on how to fix it would be greatly appreciated.
<?
/*
================================================================================
EvalMath - PHP Class to safely evaluate math expressions
Copyright (C) 2005 Miles Kaufmann <http://www.twmagic.com/>
================================================================================
NAME
EvalMath - safely evaluate math expressions
SYNOPSIS
<?
include('evalmath.class.php');
$m = new EvalMath;
// basic evaluation:
$result = $m->evaluate('2+2');
// supports: order of operation; parentheses; negation; built-in functions
$result = $m->evaluate('-8(5/2)^2*(1-sqrt(4))-8');
// create your own variables
$m->evaluate('a = e^(ln(pi))');
// or functions
$m->evaluate('f(x,y) = x^2 + y^2 - 2x*y + 1');
// and then use them
$result = $m->evaluate('3*f(42,a)');
?>
DESCRIPTION
Use the EvalMath class when you want to evaluate mathematical expressions
from untrusted sources. You can define your own variables and functions,
which are stored in the object. Try it, it's fun!
METHODS
$m->evalute($expr)
Evaluates the expression and returns the result. If an error occurs,
prints a warning and returns false. If $expr is a function assignment,
returns true on success.
$m->e($expr)
A synonym for $m->evaluate().
$m->vars()
Returns an associative array of all user-defined variables and values.
$m->funcs()
Returns an array of all user-defined functions.
PARAMETERS
$m->suppress_errors
Set to true to turn off warnings when evaluating expressions
$m->last_error
If the last evaluation failed, contains a string describing the error.
(Useful when suppress_errors is on).
AUTHOR INFORMATION
Copyright 2005, Miles Kaufmann.
LICENSE
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
1 Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. The name of the author may not be used to endorse or promote
products derived from this software without specific prior written
permission.
THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
class EvalMath {
var $suppress_errors = false;
var $last_error = null;
var $v = array('e'=>2.71,'pi'=>3.14); // variables (and constants)
var $f = array(); // user-defined functions
var $vb = array('e', 'pi'); // constants
var $fb = array( // built-in functions
'sin','sinh','arcsin','asin','arcsinh','asinh',
'cos','cosh','arccos','acos','arccosh','acosh',
'tan','tanh','arctan','atan','arctanh','atanh',
'sqrt','abs','ln','log');
function EvalMath() {
// make the variables a little more accurate
$this->v['pi'] = pi();
$this->v['e'] = exp(1);
}
function e($expr) {
return $this->evaluate($expr);
}
function evaluate($expr) {
$this->last_error = null;
$expr = trim($expr);
if (substr($expr, -1, 1) == ';') $expr = substr($expr, 0, strlen($expr)-1); // strip semicolons at the end
//===============
// is it a variable assignment?
if (preg_match('/^\s*([a-z]\w*)\s*=\s*(.+)$/', $expr, $matches)) {
if (in_array($matches[1], $this->vb)) { // make sure we're not assigning to a constant
return $this->trigger("cannot assign to constant '$matches[1]'");
}
if (($tmp = $this->pfx($this->nfx($matches[2]))) === false) return false; // get the result and make sure it's good
$this->v[$matches[1]] = $tmp; // if so, stick it in the variable array
return $this->v[$matches[1]]; // and return the resulting value
//===============
// is it a function assignment?
} elseif (preg_match('/^\s*([a-z]\w*)\s*\(\s*([a-z]\w*(?:\s*,\s*[a-z]\w*)*)\s*\)\s*=\s*(.+)$/', $expr, $matches)) {
$fnn = $matches[1]; // get the function name
if (in_array($matches[1], $this->fb)) { // make sure it isn't built in
return $this->trigger("cannot redefine built-in function '$matches[1]()'");
}
$args = explode(",", preg_replace("/\s+/", "", $matches[2])); // get the arguments
if (($stack = $this->nfx($matches[3])) === false) return false; // see if it can be converted to postfix
for ($i = 0; $i<count($stack); $i++) { // freeze the state of the non-argument variables
$token = $stack[$i];
if (preg_match('/^[a-z]\w*$/', $token) and !in_array($token, $args)) {
if (array_key_exists($token, $this->v)) {
$stack[$i] = $this->v[$token];
} else {
return $this->trigger("undefined variable '$token' in function definition");
}
}
}
$this->f[$fnn] = array('args'=>$args, 'func'=>$stack);
return true;
//===============
} else {
return $this->pfx($this->nfx($expr)); // straight up evaluation, woo
}
}
function vars() {
$output = $this->v;
unset($output['pi']);
unset($output['e']);
return $output;
}
function funcs() {
$output = array();
foreach ($this->f as $fnn=>$dat)
$output[] = $fnn . '(' . implode(',', $dat['args']) . ')';
return $output;
}
//===================== HERE BE INTERNAL METHODS ====================\\
// Convert infix to postfix notation
function nfx($expr) {
$index = 0;
$stack = new EvalMathStack;
$output = array(); // postfix form of expression, to be passed to pfx()
$expr = trim(strtolower($expr));
$ops = array('+', '-', '*', '/', '^', '_');
$ops_r = array('+'=>0,'-'=>0,'*'=>0,'/'=>0,'^'=>1); // right-associative operator?
$ops_p = array('+'=>0,'-'=>0,'*'=>1,'/'=>1,'_'=>1,'^'=>2); // operator precedence
$expecting_op = false; // we use this in syntax-checking the expression
// and determining when a - is a negation
if (preg_match("/[^\w\s+*^\/()\.,-]/", $expr, $matches)) { // make sure the characters are all good
return $this->trigger("illegal character '{$matches[0]}'");
}
while(1) { // 1 Infinite Loop ;)
$op = substr($expr, $index, 1); // get the first character at the current index
// find out if we're currently at the beginning of a number/variable/function/parenthesis/operand
$ex = preg_match('/^([a-z]\w*\(?|\d+(?:\.\d*)?|\.\d+|\()/', substr($expr, $index), $match);
//===============
if ($op == '-' and !$expecting_op) { // is it a negation instead of a minus?
$stack->push('_'); // put a negation on the stack
$index++;
} elseif ($op == '_') { // we have to explicitly deny this, because it's legal on the stack
return $this->trigger("illegal character '_'"); // but not in the input expression
//===============
} elseif ((in_array($op, $ops) or $ex) and $expecting_op) { // are we putting an operator on the stack?
if ($ex) { // are we expecting an operator but have a number/variable/function/opening parethesis?
$op = '*'; $index--; // it's an implicit multiplication
}
// heart of the algorithm:
while($stack->count > 0 and ($o2 = $stack->last()) and in_array($o2, $ops) and ($ops_r[$op] ? $ops_p[$op] < $ops_p[$o2] : $ops_p[$op] <= $ops_p[$o2])) {
$output[] = $stack->pop(); // pop stuff off the stack into the output
}
// many thanks: http://en.wikipedia.org/wiki/Reverse_Polish_notation#The_algorithm_in_detail
$stack->push($op); // finally put OUR operator onto the stack
$index++;
$expecting_op = false;
//===============
} elseif ($op == ')' and $expecting_op) { // ready to close a parenthesis?
while (($o2 = $stack->pop()) != '(') { // pop off the stack back to the last (
if (is_null($o2)) return $this->trigger("unexpected ')'");
else $output[] = $o2;
}
if (preg_match("/^([a-z]\w*)\($/", $stack->last(2), $matches)) { // did we just close a function?
$fnn = $matches[1]; // get the function name
$arg_count = $stack->pop(); // see how many arguments there were (cleverly stored on the stack, thank you)
$output[] = $stack->pop(); // pop the function and push onto the output
if (in_array($fnn, $this->fb)) { // check the argument count
if($arg_count > 1)
return $this->trigger("too many arguments ($arg_count given, 1 expected)");
} elseif (array_key_exists($fnn, $this->f)) {
if ($arg_count != count($this->f[$fnn]['args']))
return $this->trigger("wrong number of arguments ($arg_count given, " . count($this->f[$fnn]['args']) . " expected)");
} else { // did we somehow push a non-function on the stack? this should never happen
return $this->trigger("internal error");
}
}
$index++;
//===============
} elseif ($op == ',' and $expecting_op) { // did we just finish a function argument?
while (($o2 = $stack->pop()) != '(') {
if (is_null($o2)) return $this->trigger("unexpected ','"); // oops, never had a (
else $output[] = $o2; // pop the argument expression stuff and push onto the output
}
// make sure there was a function
if (!preg_match("/^([a-z]\w*)\($/", $stack->last(2), $matches))
return $this->trigger("unexpected ','");
$stack->push($stack->pop()+1); // increment the argument count
$stack->push('('); // put the ( back on, we'll need to pop back to it again
$index++;
$expecting_op = false;
//===============
} elseif ($op == '(' and !$expecting_op) {
$stack->push('('); // that was easy
$index++;
$allow_neg = true;
//===============
} elseif ($ex and !$expecting_op) { // do we now have a function/variable/number?
$expecting_op = true;
$val = $match[1];
if (preg_match("/^([a-z]\w*)\($/", $val, $matches)) { // may be func, or variable w/ implicit multiplication against parentheses...
if (in_array($matches[1], $this->fb) or array_key_exists($matches[1], $this->f)) { // it's a func
$stack->push($val);
$stack->push(1);
$stack->push('(');
$expecting_op = false;
} else { // it's a var w/ implicit multiplication
$val = $matches[1];
$output[] = $val;
}
} else { // it's a plain old var or num
$output[] = $val;
}
$index += strlen($val);
//===============
} elseif ($op == ')') { // miscellaneous error checking
return $this->trigger("unexpected ')'");
} elseif (in_array($op, $ops) and !$expecting_op) {
return $this->trigger("unexpected operator '$op'");
} else { // I don't even want to know what you did to get here
return $this->trigger("an unexpected error occured");
}
if ($index == strlen($expr)) {
if (in_array($op, $ops)) { // did we end with an operator? bad.
return $this->trigger("operator '$op' lacks operand");
} else {
break;
}
}
while (substr($expr, $index, 1) == ' ') { // step the index past whitespace (pretty much turns whitespace
$index++; // into implicit multiplication if no operator is there)
}
}
while (!is_null($op = $stack->pop())) { // pop everything off the stack and push onto output
if ($op == '(') return $this->trigger("expecting ')'"); // if there are (s on the stack, ()s were unbalanced
$output[] = $op;
}
return $output;
}
// evaluate postfix notation
function pfx($tokens, $vars = array()) {
if ($tokens == false) return false;
$stack = new EvalMathStack;
foreach ($tokens as $token) { // nice and easy
// if the token is a binary operator, pop two values off the stack, do the operation, and push the result back on
if (in_array($token, array('+', '-', '*', '/', '^'))) {
if (is_null($op2 = $stack->pop())) return $this->trigger("internal error");
if (is_null($op1 = $stack->pop())) return $this->trigger("internal error");
switch ($token) {
case '+':
$stack->push($op1+$op2); break;
case '-':
$stack->push($op1-$op2); break;
case '*':
$stack->push($op1*$op2); break;
case '/':
if ($op2 == 0) return $this->trigger("division by zero");
$stack->push($op1/$op2); break;
case '^':
$stack->push(pow($op1, $op2)); break;
}
// if the token is a unary operator, pop one value off the stack, do the operation, and push it back on
} elseif ($token == "_") {
$stack->push(-1*$stack->pop());
// if the token is a function, pop arguments off the stack, hand them to the function, and push the result back on
} elseif (preg_match("/^([a-z]\w*)\($/", $token, $matches)) { // it's a function!
$fnn = $matches[1];
if (in_array($fnn, $this->fb)) { // built-in function:
if (is_null($op1 = $stack->pop())) return $this->trigger("internal error");
$fnn = preg_replace("/^arc/", "a", $fnn); // for the 'arc' trig synonyms
if ($fnn == 'ln') $fnn = 'log';
eval('$stack->push(' . $fnn . '($op1));'); // perfectly safe eval()
} elseif (array_key_exists($fnn, $this->f)) { // user function
// get args
$args = array();
for ($i = count($this->f[$fnn]['args'])-1; $i >= 0; $i--) {
if (is_null($args[$this->f[$fnn]['args'][$i]] = $stack->pop())) return $this->trigger("internal error");
}
$stack->push($this->pfx($this->f[$fnn]['func'], $args)); // yay... recursion!!!!
}
// if the token is a number or variable, push it on the stack
} else {
if (is_numeric($token)) {
$stack->push($token);
} elseif (array_key_exists($token, $this->v)) {
$stack->push($this->v[$token]);
} elseif (array_key_exists($token, $vars)) {
$stack->push($vars[$token]);
} else {
return $this->trigger("undefined variable '$token'");
}
}
}
// when we're out of tokens, the stack should have a single element, the final result
if ($stack->count != 1) return $this->trigger("internal error");
return $stack->pop();
}
// trigger an error, but nicely, if need be
function trigger($msg) {
$this->last_error = $msg;
if (!$this->suppress_errors) trigger_error($msg, E_USER_WARNING);
return false;
}
}
// for internal use
class EvalMathStack {
var $stack = array();
var $count = 0;
function push($val) {
$this->stack[$this->count] = $val;
$this->count++;
}
function pop() {
if ($this->count > 0) {
$this->count--;
return $this->stack[$this->count];
}
return null;
}
function last($n=1) {
return $this->stack[$this->count-$n];
}
}
| 0 | 0 | 0 | 0 | 1 | 0 |
I have two points in space, L1 and L2 that defines two points on a line.
I have three points in space, P1, P2 and P3 that 3 points on a plane.
So given these inputs, at what point does the line intersect the plane?
Fx. the plane equation A*x+B*y+C*z+D=0 is:
A = p1.Y * (p2.Z - p3.Z) + p2.Y * (p3.Z - p1.Z) + p3.Y * (p1.Z - p2.Z)
B = p1.Z * (p2.X - p3.X) + p2.Z * (p3.X - p1.X) + p3.Z * (p1.X - p2.X)
C = p1.X * (p2.Y - p3.Y) + p2.X * (p3.Y - p1.Y) + p3.X * (p1.Y - p2.Y)
D = -(p1.X * (p2.Y * p3.Z - p3.Y * p2.Z) + p2.X * (p3.Y * p1.Z - p1.Y * p3.Z) + p3.X * (p1.Y * p2.Z - p2.Y * p1.Z))
But what about the rest?
| 0 | 0 | 0 | 0 | 1 | 0 |
I'm thinking about writing a program that asks the user to think of an object(a physical one) and then it asks questions about the object and tries to figure out what the user was thinking. (Similar to http://20q.net)
I tried to do it in Python but figured my approach was naive and would be very inefficient. How would you guys do this?
| 0 | 1 | 0 | 0 | 0 | 0 |
I'm looking for an algorithm that will determine if the current mahjong hand is a winning one. If you are not familiar with the game, here's the basic idea (simplified):
There are three suits of tiles, each containing tiles ranked 1-9. There are also special tiles, seven types of them. Each tile exists in four copies, so there are 36 tiles of each suit and 28 special tiles.
A hand has 14 tiles in it.
A chow is a set of three tiles of a single suit with consecutive ranks.
A pong is a set of three identical tiles.
A kong is a set of four identical tiles.
A pair is a set of two identical tiles.
A winning hand is one in which the tiles form any number of chows, pongs, and/or kongs and one pair.
The hand is sorted by suit and then by rank. My idea is something like this:
Mark all tiles as unvisited and nonwinning.
Visit first unvisited tile.
Check subsequent tiles until a chow, pong, or a kong is encountered, or until there is no possibility of it. If a combination is completed, mark all participating tiles as visited and winning
If all tiles have been visited, check if all of them are winning. If not all tiles have been visited, go to 2.
The problem is that once a tile is a part of a combination is cannot be a member of any other combination, one that might make the hand a winning one.
Any ideas for a working algorithm?
| 0 | 1 | 0 | 0 | 0 | 0 |
I'm looking to see if built in with the math library in python is the nCr (n Choose r) function:
I understand that this can be programmed but I thought that I'd check to see if it's already built in before I do.
| 0 | 0 | 0 | 0 | 1 | 0 |
Someone asked me this question during an interview. How would you go about this? This is not a random BS question but has good math behind it. The profile was for an analytic position so they wanted someone with good math skills. I couldn't really figure out a good way of calculating this.
Here is some data I collected after the interview which might be helpful:
Height growth depends mainly on genetic factors, diet, standard of life etc. Human grow rate is fastest at birth rapidly declining between 0 & 2, tapering to a slowly declining rate & then a rapid rise at puberty say 13 which gives you a second maxima followed by a steady decline to 0 at roughly age 18.
You may use this data or make your own assumptions to answer the question. Also how would you go about answering based on just the title of this question, knowing that you need to demonstrate strong math skills?
| 0 | 0 | 0 | 0 | 1 | 0 |
I am calculating a value ( that should reflect the sin of an angle between a direction vector and the XZ plane ) like this
angle_between_direction_and_Xplane = (Math.Abs(enemyShip_.orientation.Forward.Y) / Math.Sqrt(Math.Pow(enemyShip_.orientation.Forward.X, 2) + Math.Pow(enemyShip_.orientation.Forward.Y, 2) + Math.Pow(enemyShip_.orientation.Forward.Z, 2)));
and it seems to work just fine . When the object is perpendicular to the ground the angle_between_direction_and_Xplane is near to 1 and when it is paralel to XZ plane it is near to 0 .
When i apply Math.Asin i would like to get a angle ( like 70 or 20 degrees ) but instead i get values around 1 . Am I using it wrong ?
| 0 | 0 | 0 | 0 | 1 | 0 |
The language I am using is C#.
I have the folowing dillema.
DateTime A, DateTime B. If A < B then I have to calculate the number of days per year in that timespan and multiply it by a coeficient that corresponds to that year.
My problem is the fact that it can span multiple years.
For example:
Nr of Days in TimeSpan for 2009 * coef for 2009 + Nr of Days in TimeSpan for 2010 * coef for 2010 + etc
| 0 | 0 | 0 | 0 | 1 | 0 |
I'm implementing a graph (as in Vertices, Edges, not cartesian). I'm modelling the graph as a physical collection of Nodes (a class I've made).
I want to have a collection of Forces, as Vectors (in the Maths sense), to represent the forces acting upon each node, and ideally I would like to be able to perform a lookup with a Node as a key, which sounds to me like some kind of Hash Lookup Table.
What's a good collection to use, or will I have to make my own?
If anything needs clarifying, just ask.
Thanks
| 0 | 0 | 0 | 0 | 1 | 0 |
I'm trying to convert calculator input to LaTeX. if a user inputs this:
(3x^(x+(5/x)+(x/33))+y)/(32 + 5)
I have to convert it to this:
frac{3x^(x+frac{5}{x}+frac{x}{33})+y}{32 + 5x}
however I am having issues with determining when a numerator begins and ends. Any suggestions?
| 0 | 0 | 0 | 0 | 1 | 0 |
Are there standard rules engine/algorithms around AI that would predict the user taste on a particular kind of product like clothes.
I know it's one thing all e-commerce website will kill for. But I am looking out for theoretical patterns defined out there which would help make that prediction in a better way, if not accurately.
| 0 | 1 | 0 | 0 | 0 | 0 |
I am doing some sse vector3 math.
Generally, I set the 4th digit of my vector to 1.0f, as this makes most of my math work, but sometimes I need to set it to 0.0f.
So I want to change something like:
(32.4f, 21.2f, -4.0f, 1.0f) to (32.4f, 21.2f, -4.0f, 0.0f)
I was wondering what the best method to doing so would be:
Convert to 4 floats, set 4th float, send back to SSE
xor a register with itself, then do 2 shufps
Do all the SSE math with 1.0f and then set the variables to what they should be when finished.
Other?
Note: The vector is already in a SSE register when I need to change it.
| 0 | 0 | 0 | 0 | 1 | 0 |
I am writing a "triangle solver" app for Android, and I was wondering if it would be possible to implement exact values for trig ratios and radian measures. For example, 90 degrees would be output as "pi / 2" instead of 1.57079632679...
I know that in order to get the exact value for a radian measure, I would divide it by pi and convert it to a fraction. I don't know how I would convert the decimal to a fraction.
like this:
int decimal = angleMeasure / Math.PI;
someMethodToTurnItIntoAFraction(decimal);
I don't even know where to begin with the trig ratios.
| 0 | 0 | 0 | 0 | 1 | 0 |
I am trying to centre a line of text, of known width along a line specified as start and end coordinates.
The purpose is to write text around a polygon, so the lines are not always horizontal.
Currently I have the following function which takes the start x and y and the finish x and y of a line and the width of the text (in pixels).
The text will be drawn starting at x1, y1 at the correct angle to follow the line.
To centre this text on the line I have tried to calculate left padding in pixels which should be applied to x1, y1 to move the text the correct amount from its left origin.
The following function is my attempt at modifying the coordinates to implement the above concept. But its not quite right. I end up with text slightly off line, sometimes x is out sometimes y, depends on the face but neither x or y is correct.
private function CenterTextOnLine(&$x1, &$y1, &$x2, &$y2, $width)
{
$distance = $this->getDistance($x1, $y1, $x2, $y2);
//calculate the left padding required in pixels
$padding = ($distance - $width) / 2;
//what factor do we need to alter x1, y1 by?
$factor = ($distance / $padding);
$gradient = ($y2-$y1)/($x2-$x1); //gradient to alter y by
$x1 += abs($x2-$x1) / $factor; //move start x by factor
$y1 += ($gradient / $factor); //add factor of gradient to start y
return;
}
If anyone can see my error, or knows an algorithm for this purpose, I would very much appreciate your input.
Thanks for your time.
| 0 | 0 | 0 | 0 | 1 | 0 |
Its a very tiny bit of math and more a question of the most efficient, most elegant way possible.
If I give an integer such as
1.50
or
1.22
or
10.99
How can I get rid of the number to the left of the decimal and output the right side as an integer or float, for example
.50 or 50
.22 or 22
.99 or 99
It matters what the fastest way to do it is. I would rather not turn it into a string if possible.
Thanks for the help.
BR
| 0 | 0 | 0 | 0 | 1 | 0 |
I've inherited a Visual Studio/VB.Net numerical simulation project that has a likely inefficient calculation. Profiling indicates that the function is called a lot (1 million times plus) and spends about 50% of the overall calculation within this function. Here is the problematic portion
Result = (A * (E ^ C)) / (D ^ C * B) (where A-C are local double variables and D & E global double variables)
Result is then compared to a threshold which might have additional improvements as well, but I'll leave them another day
any thoughts or help would be appreciated
Steve
| 0 | 0 | 0 | 0 | 1 | 0 |
Like everyone else, I am doing a Thrust clone just to brush up. I have arrived at the stage where the ship picks up the pod.
Essentially I have two masses (consider centre of sphere only) connected with a rigid, massless rod. L never changes, doesn't break.
In this case, the ship(ma) has mass 1.0, and the pod(mb) has mass 2.0. What is the math required to compute new positions? When I apply thrust to the ship(ma), how do I apply that to pod(mb)? (and make it swing around as expected) Doing the ship itself was straight forward, usual velx-=sin(angle)*thrust, vely+=cos(angle)*thrust. posx+=velx. etc. I know I used to know how to do this, but school was soo many years ago.
| 0 | 0 | 0 | 0 | 1 | 0 |
I have a window that needs to be constrained within another window. In order to do this,
I hook into the SizeChanged event on the top level window....and in that event I need to adjust the second window so that it is aligned to the nearest edge only if there is an intersection between the two i.e if the smaller window gets outside the boundary of the bigger window.
I do a lot of math calculation to get this...and im still not near to the solution!
Im having trouble doing this because it involves a lot of messy code I was wondering if any of you guys had an easier solution to this?
Basically im dealing with 2 rectangles and I need to ensure that when the size of the bigger rectangle changes...if there is an intersection between the two, then the smaller rectangle should align itself to the edge of the bigger rectangle so that the smaller rectangle is within the bigger rectangle.
Could be a simple math problem in C# forms?
Any suggestions are welcome thanks!
| 0 | 0 | 0 | 0 | 1 | 0 |
Conceptually, I need to multiply the probabilities of each event in a coincidence. Since there may be very many events involved, I have the computer add the logarithms to avoid underflow.
But suddenly I can't convince myself that I should initialize the return value to zero before I start adding. I know zero is the identity element for addition, and I remember this is how I do it, but, looking at a graph of the logarithm, I can clearly see that the antilog of zero is negative infinity.
So initializing the return value to zero should be equivalent to multiplying all my probabilities by negative infinity, which is definitely not correct. What am I doing wrong?
| 0 | 0 | 0 | 0 | 1 | 0 |
I need to create a simple calculator that computes 1% of the value submitted by the user. I also need to round it (floor) to the tenth part after colon.
Examples:
input 1% output
12.34 0.1234 0.10
2345.34 23.4534 23.40
More info:
- users will submit monetary values. They can use dots or comma to separate the parts of the value. Both inputs 123.45 and 123,45 are valid.
- I need to calculate 1% of it, round it and display in "user friendly" form, for example XX.YY
I created following function so far. But it rounds the value in odd way. For example, for input "123.45" the output is 1.2000000000000002 (should be 1.20).
function calc(val)
{
var x = 0.1*Math.floor(0.1*val);
alert("your 1% is:
"+x);
}
Javascript treats only values with dots as numbers. How can I easily convert values with commas to numbers?
And how to display the outcome with desired precision?
| 0 | 0 | 0 | 0 | 1 | 0 |
So I'm writing a graphing calculator. So far I have a semi-functional grapher, however, I'm having a hard time getting a good balance between accurate graphs and smooth looking curves.
The current implementation (semi-pseudo-code) looks something like this:
for (float i = GraphXMin; i <= GraphXMax; i++)
{
PointF P = new PointF(i, EvaluateFunction(Function, i)
ListOfPoints.Add(P)
}
Graphics.DrawCurve(ListOfPoints)
The problem with this is since it only adds a point at every integer value, graphs end up distorted when their turning points don't fall on integers (e.g. sin(x)^2).
I tried incrementing i by something smaller (like 0.1), which works, but the graph looks very rough.
I am using C# and GDI+. I have SmoothingMethod set to AntiAlias, so that's not the problem, as you can see from the first graph. Is there some sort of issue with drawing curves with a lot of points? Should the points perhaps be positioned exactly on pixels?
I'm sure some of you have worked on something very similar before, so any suggestions? While you're at it, do you have any suggestions for graphing functions with asymptotes? e.g. 1/x^2
P.S. I'm not looking for a library that does all this - I want to write it myself.
| 0 | 0 | 0 | 0 | 1 | 0 |
I want to show some effect (animate) with the help of jQuery during the time that should be calculated based on how many results are found for a particular needle. The rule is that the effect should continue no longer than 5 minutes and at the very least be 5 seconds long.
So, here's what I do in particular. I search a database for a particular word the user inputs and count the results. Then I search a myself defined word in the same database and count the results. If there are more the latter results than the former results, I need to calculate how long to show the effect. The more the latter results found, the longer the time the effect should continue. Plus, I need to obey the rule: no longer than 5 minutes, no less than 5 seconds.
I need that to be accurate at best.
That may be a stupid question but I cannot figure out on my own how to calculate the time! :)
| 0 | 0 | 0 | 0 | 1 | 0 |
Got a question about C++ Pointer addition. If you look at the screen shot provided you can basically see I'm doing a memcpy(m_pBuf + m_iWritePtr .... and this memory pointer addition is not working as expected.
I had thought that the addition of m_pBuf + m_iWritePtr would add m_iWritePtr bytes to my memory address m_pBuf. m_pBuf is a pointer to a structure array; i.e. (T *)m_pBuf = new T[cnt] where T is a typename and cnt is the number of T objects allocated. T is, in this case a simple structure. The sizeof(T) in this case is 260.
The memcpy call is throwing a fault and I know my pointer math is wrong but I'm not 100% sure why. The memcpy is coded to, I thought, to take the base address and add some n * 260 bytes to get an offset into the buffer. NOTE: This code use to work when this was not a template implementation and T was simply a char *. Now that T is a template of some typename, the offset addition no longer works as expected.
So if you look at the screen shot below, here are the results of various calculations/references I did using the compiler's debugger/inspector and a calculator:
The memory address of m_pBuf = 0x01E7E0E0
The memory address of m_pBuf[1] = 0x01E8EE04
the memory address of m_pBuf+1 = 0x01E8EE04
the memory address of m_pBuf++ = 0x01E8EBFC
the memory address of m_pBuf+260 = 0x01E7E1E4 (the calculator's result)
I'm trying to understand what's going on here. The first two seem correct but I don't understand why none of these are equal. This is 32bit compiler on Windows 7-64bit.
To further explain, this is a ring buffer of type T with a size of n * T objects of storage. Here is the code:
template<typename T>
bool TMsgBuffer<T>::PutMsgEx(T *pBuf, unsigned long nObjCount )
{
bool bResult = false;
unsigned long MaxWriteSize, nPutLen;
Lock();
MaxWriteSize = GetMaxWriteSize(); // this returns size of my buffer in total.
nPutLen = nObjCount * m_nObjSize; // m_nObjSize is set else where to sizeof(T)
if(nPutLen <= MaxWriteSize)
{
// easy case, no wrapping
if( m_iWritePtr + nPutLen <= m_nBufSize )
{
memcpy(m_pBuf + m_iWritePtr, pBuf, nPutLen);
m_iWritePtr += nPutLen;
}
else // need to wrap
{
m_iFirstChunkSize = m_nBufSize - m_iWritePtr;
m_iSecondChunkSize = nPutLen - m_iFirstChunkSize;
memcpy(m_pBuf + m_iWritePtr, pBuf, m_iFirstChunkSize );
memcpy(m_pBuf, pBuf + m_iFirstChunkSize, m_iSecondChunkSize );
m_iWritePtr = m_iSecondChunkSize;
}
//m_MsgCount++;
m_MsgCount+= nObjCount;
bResult = true;
}
Unlock();
return bResult;
}
| 0 | 0 | 0 | 0 | 1 | 0 |
Under the user generated posts on my site, I have an Amazon-like rating system:
Was this review helpful to you: Yes | No
If there are votes, I display the results above that line like so:
5 of 8 people found this reply helpful.
I would like to sort the posts based upon these rankings. If you were ranking from most helpful to least helpful, how would you order the following posts?
a) 1/1 = 100% helpful
b) 2/2 = 100% helpful
c) 999/1000 = 99.9% helpful
b) 3/4 = 75% helpful
e) 299/400 = 74.8% helpful
Clearly, its not right to sort just on the percent helpful, somehow the total votes should be factored in. Is there a standard way of doing this?
UPDATE:
Using Charles' formulas to calculate the Agresti-Coull lower range and sorting on it, this is how the above examples would sort:
1) 999/1000 (99.9%) = 95% likely to fall in 'helpfulness' range of 99.2% to 100%
2) 299/400 (74.8%) = 95% likely to fall in 'helpfulness' range of 69.6% to 79.3%
3) 3/4 (75%) = 95% likely to fall in 'helpfulness' range of 24.7% to 97.5%
4) 2/2 (100%) = 95% likely to fall in 'helpfulness' range of 23.7% to 100%
5) 1/1 (100%) = 95% likely to fall in 'helpfulness' range of 13.3% to 100%
Intuitively, this feels right.
UPDATE 2:
From an application point of view, I don't want to be running these calculations every time I pull up a list of posts. I'm thinking I'll either update and store the Agresti-Coull lower bound either on a regular, cron-driven schedule (updating only those posts which have received a vote since the last run) or update it whenever a new vote is received.
| 0 | 0 | 0 | 0 | 1 | 0 |
Possible Duplicate:
How do you detect where two line segments intersect?
Can someone provide an algorithm or C code for determining if two line segments intersect?
| 0 | 0 | 0 | 0 | 1 | 0 |
We have an array of elements a1,a2,...aN from an alphabet E. Assuming |N| >> |E|.
For each symbol of the alphabet we define an unique integer priority = V(sym). Let's define V{i} := V(symbol(ai)) for the simplicity.
How can I find the priority function V for which:
Count(i)->MAX | V{i} < V{i+1}
In other words, I need to find the priorities / permutation of the alphabet for which the number of positions i, satisfying the condition V{i}<V{i+1}, is maximum.
Edit-1: Please, read carefully. I'm given an array ai and the task is to produce a function V. It's not about sorting the input array with a priority function.
Edit-2: Example
E = {a,b,c}; A = 'abcab$'; (here $ = artificial termination symbol, V{$}=+infinity)
One of the optimal priority functions is: V{a}=1,V{b}=2,V{c}=3, which gives us the following signs between array elements: a<b<c>a<b<$, resulting in 4 '<' signs of 5 total.
| 0 | 0 | 0 | 0 | 1 | 0 |
I'm writing an AI for an RTS game, using the API the game offers. One thing I want to do is determine a set of line segments bounding the enemy nation, However, the game only offers a function which tells me the teamID of a single 2D point of territory.
Queries to the game AI are incredibly expensive to execute, so I need to keep the number of queries to an absolute minimum, even if this means occasionally getting a slightly worse quality answer. It's also better to overestimate the area of the enemy territory than underestimate it.
How can I efficiently determine a set of bounding lines, around a non convex area of space, using the minimum number of queries?
Nb: Bonus points for answer written in Lua, but Pseudo-code is fine too.
| 0 | 0 | 0 | 0 | 1 | 0 |
Could you give an example of classification of 4 classes using Support Vector Machines (SVM) in matlab something like:
atribute_1 atribute_2 atribute_3 atribute_4 class
1 2 3 4 0
1 2 3 5 0
0 2 6 4 1
0 3 3 8 1
7 2 6 4 2
9 1 7 10 3
| 0 | 1 | 0 | 1 | 0 | 0 |
A full game or application is not needed; just a core library that ideally can:
be competitive against a human
have configurable difficulty
have customizable moves (I might need some unique moves that don't exist in traditional chess)
The platform is a closed system that can only run Lua, so I don't even have access to run a C++ engine via Lua bindings. I would need to translate the C++ to Lua, which I'd ideally like to avoid but am not opposed to if there's no other way (unless it's a boatload of code).
| 0 | 1 | 0 | 0 | 0 | 0 |
What's the best way to store and search a database of natural language sentence structure trees?
Using OpenNLP's English Treebank Parser, I can get fairly reliable sentence structure parsings for arbitrary sentences. What I'd like to do is create a tool that can extract all the doc strings from my source code, generate these trees for all sentences in the doc strings, store these trees and their associated function name in a database, and then allow a user to search the database using natural language queries.
So, given the sentence "This uploads files to a remote machine." for the function upload_files(), I'd have the tree:
(TOP
(S
(NP (DT This))
(VP
(VBZ uploads)
(NP (NNS files))
(PP (TO to) (NP (DT a) (JJ remote) (NN machine))))
(. .)))
If someone entered the query "How can I upload files?", equating to the tree:
(TOP
(SBARQ
(WHADVP (WRB How))
(SQ (MD can) (NP (PRP I)) (VP (VB upload) (NP (NNS files))))
(. ?)))
how would I store and query these trees in a SQL database?
I've written a simple proof-of-concept script that can perform this search using a mix of regular expressions and network graph parsing, but I'm not sure how I'd implement this in a scalable way.
And yes, I realize my example would be trivial to retrieve using a simple keyword search. The idea I'm trying to test is how I might take advantage of grammatical structure, so I can weed-out entries with similar keywords, but a different sentence structure. For example, with the above query, I wouldn't want to retrieve the entry associated with the sentence "Checks a remote machine to find a user that uploads files." which has similar keywords, but is obviously describing a completely different behavior.
| 0 | 1 | 0 | 1 | 0 | 0 |
I seem to have a mental block, and cannot progress with the following problem. Basically, I want to find all possible squares in a given number, i.e. N = S*S*A, where N in given number, S*S is a square, and A is some other number. And I need to find all possible combinations of that kind.
So far I have factorized the number N in a sequence of prime number, and build a Map, where keys are unique prime numbers in the sequence, and values are number of occurrences of this prime number.
For example, for some number there might be such sequence:
2 2 2 3 3 5 5 5 5 7 7 7 7 7,
thus, the squares should be 4, 9, 25, 49, 36, 100, 196, 225, 441, 1225. For such sequence, I will have the following map:
2 3
3 2
5 4
7 5
Next, I decrease odd values by one:
2 2
3 2
5 4
7 4
The main question is how to get squares written above from this map. My idea was to run 2 loops (no idea how efficient that is):
for(Map.Entry<BigInteger, Integer> entry : frequency.entrySet()) {
for(Map.Entry<BigInteger, Integer> ientry : frequency.entrySet()) {
}
}
It is obvious how to multiply all pairs of keys from the map, but I cannot come up with conditions I have to impose to take multiplicities into account.
Thanks you very much in advance!
P.s. Is there any good way without nested loops?
| 0 | 0 | 0 | 0 | 1 | 0 |
I would like to use the accelerometer to move my player sprite.
If the sprite is going straight and the player tilts a little to the left, the sprite should rotate a little bit to the left, and same for the right.
I also want to detect how much the player has tilted the device and turn the sprite accordingly.
e.g. If the player tilts the device a lot the sprite should rotate 90 degrees rather than 45 for a quick tilt in a direction.
How does one do this. Detect the device movement in any direction, and for a small movement, the sprite should rotate less and for a larger rotation the sprite should rotate more.
I have experimented a little and dont get the results. Some times it works for clockwise rotations to the up, right and down movements, but not for the left movements.
What is the math behind this. An example would be the way a device detects its orientation and rotates the screen.
How does one do this correctly?
| 0 | 0 | 0 | 0 | 1 | 0 |
So a friend of mine had an interesting homework assignment. Her task was to create a diamond based on user input. Sample diamond based on input of (5) is:
************
***** *****
**** ****
*** ***
** **
*----------*
** **
*** ***
**** ****
***** *****
************
Not too hard to do using nested loops, or recursion, however you like.
As a challenge to myself I set out to solve it with some extra criteria:
Only allowed to use 1 loop
Not allowed to use any variables other than the input and your loop index
I've gotten 2/3 of the way, but I know that I'm just probing blindly and I'd like to actually understand the solution.
It is somewhat similar to this Diamond Pattern, but their code uses all the constructs I'm trying to avoid.
The most relevant information I've found so far is on quadratic equations, but either I don't have enough data to make viable use of them or I'm just not nerdy enough to figure it out.
Here's where I've gotten so far:
******
*****
****
***
**
*
**
***
****
*****
******
With this code:
<script type="text/javascript">
for(x=1;x<=(lines*2+2)*lines*2+(lines*2+2);x++) {
if( ((x-1)%(lines*2+2)) <= Math.floor(((Math.abs(( (x-1)/(lines*2+2))%(lines*2+2) -lines)-0.51)+1)) ) {
document.write("*");
}
if((x%(lines*2+2))==0) { document.write("
"); }
}
</script>
Any help is appreciated. Thanks!
Edit:
I missed a major part of the assignment. Another of the requirements is that you only print out a single character at a time.
There has to be some sort of mathematical relationship between row number and column number that is exploitable.
| 0 | 0 | 0 | 0 | 1 | 0 |
Here it goes.
I have been thinking about this for a long time, and havent really been able to put up a proper way to do it yet. I havent implemented anything yet, as im still designing the thing.
The idea is that i crawl a website for internal links, i got this settled, its easy, but after the crawling, i end up with an array with lots of links, and how many times those particular link appears on the site that i crawled (and how they're connected).
With this huge array, i want to draw a graph somehow. Assuming i can handle the data correctly, the real question here is how i can draw this in a image by the use of the GD library.
I figured if theres less than 12 elements, i can align them up on a unit circle spacing them up as a circle and then connecting them accordingly, so anything up to 12 elements shouldn't be a problem, but if theres more than 12, it could be awesome getting them lined up like this http://nayena.com/stackoverflow/graph.png Or well, thats just a rough drawing, but i guess its just to prove a point.
So i'm here looking for guidance or tips towards getting the math down to getting the stuff lined up in a good way.
I have previously made bar-graphs, so i have little experience doing math with GD. If possible, id prefer not using some plotter-library - in the end, it gives me a better understanding on how things are supposed to be.
| 0 | 0 | 0 | 0 | 1 | 0 |
I know tl;dr;
I'll try to explain my problem without bothering you with ton's of crappy code. I'm working on a school assignment. We have pictures of smurfs and we have to find them with foreground background analysis. I have a Decision Tree in java that has all the data (HSV histograms) 1 one single node. Then tries to find the best attribute (from the histogram data) to split the tree on. Then executes the split and creates a left and a right sub tree with the data split over both node-trees. All the data is still kept in the main tree to be able to calculate the gini index.
So after 26 minutes of analysing smurfs my pc has a giant tree with splits and other data. Now my question is, can anyone give me a global idea of how to analyse a new picture and determine which pixels could be "smurf pixels". I know i have to generate a new array of data points with the HSV histograms of the new smurf and then i need to use the generated tree to determine which pixels belong to a smurf.
Can anyone give me a pointer on how to do this?
Some additional information.Every Decision Tree object has a Split object that has the best attribute to split on, the value to split on and a gini index.
If i need to provide any additional information I'd like to hear it.
| 0 | 0 | 0 | 1 | 0 | 0 |
hello please is it possible to develop a learning system based on neural network using Netbeans IDE and having success at the end? and what about blueJ, eclipse...which one do u recommend?
| 0 | 1 | 0 | 0 | 0 | 0 |
Do you know anything about the VFI5 algorithm?
some example?
This algorithm is supossed to clasiffy a data set, based on voting, but I would like to know more about it.
Thanks.
| 0 | 0 | 0 | 1 | 0 | 0 |
Converting 'small' numbers to English is not to troublesome. But if you handle BCMath Arbitrary Precision numbers then it can be.
Using code from:
http://marc.info/?l=php-general&m=99928281523866&w=2
The maximum number seems to be:
two billion one hundred forty seven
million four hundred eighty three
thousand six hundred forty seven
Anyone know a function to convert numbers bigger than that?
| 0 | 0 | 0 | 0 | 1 | 0 |
I've just started playing with GHCi. I see that list generators basically solve an equation within a given set:
Prelude> [x | x <- [1..20], x^2 == 4]
[2]
(finds only one root, as expected)
Now, why can't I solve equations with results in ℝ, given that the solution is included in the specified range?
[x | x <- [0.1,0.2..2.0], x*4 == 2]
How can I solve such equations within real numbers set?
Edit: Sorry, I meant 0.1, of course.
| 0 | 0 | 0 | 0 | 1 | 0 |
I am often faced with the problem of checking some property of trees (the graph ones) of a given size by brute force. Do you have any nice tricks for doing this? Ideally, I'd like to examine each isomorphism class only once (but after all, speed is all that matters).
Bit twiddling tricks are most welcome since n is usually less than 32 :)
I'm asking for slightly more refined algorithms than the likes of "loop through all (n-1)-edge subsets and check if they form a tree" for trees on n nodes.
| 0 | 0 | 0 | 0 | 1 | 0 |
I want to round according to arbitrary divisions, e.g. I get a number from 0 to 1 and I want to round it according to divisions into 48ths, e.g. if I get something like 5/96, i want either 2/48 or 3/48. What's a good formula to do that?
| 0 | 0 | 0 | 0 | 1 | 0 |
I'm reading a file from n servers, and I want each to download 1/nth of the file. I thought some quick integer math would work, but it doesn't seem to always work:
threads = n
thread_id = 0:n-1
filesize (in bytes) = x
starting position = thread_id*(filesize/threads)
bytes to read = (filesize/threads)
Sometimes for just the right numbers, like a 26 byte file divided up by 9 threads (I know that's ridiculous but just for example), it doesn't work out in my favor. There must be a better way. Any ideas?
| 0 | 0 | 0 | 0 | 1 | 0 |
I am new to this forum and not a native english speaker, so please be nice! :)
Here is the challenge I face at the moment:
I want to calculate the (approximate) relative coordinates of yet unknown points in a 3D euclidean space based on a set of given distances between 2 points.
In my first approach I want to ignore possible multiple solutions, just taking the first one by random.
e.g.:
given set of distances: (I think its creating a pyramid with a right-angled triangle as a base)
P1-P2-Distance
1-2-30
2-3-40
1-3-50
1-4-60
2-4-60
3-4-60
Step1:
Now, how do I calculate the relative coordinates for those points?
I figured that the first point goes to 0,0,0 so the second one is 30,0,0.
After that the third points can be calculated by finding the crossing of the 2 circles from points 1 and 2 with their distances to point 3 (50 and 40 respectively). How do I do that mathematically? (though I took these simple numbers for an easy representation of the situation in my mind). Besides I do not know how to get to the answer in a correct mathematical way the third point is at 30,40,0 (or 30,0,40 but i will ignore that).
But getting the fourth point is not as easy as that. I thought I have to use 3 spheres in calculate the crossing to get the point, but how do I do that?
Step2:
After I figured out how to calculate this "simple" example I want to use more unknown points... For each point there is minimum 1 given distance to another point to "link" it to the others. If the coords can not be calculated because of its degrees of freedom I want to ignore all possibilities except one I choose randomly, but with respect to the known distances.
Step3:
Now the final stage should be this: Each measured distance is a bit incorrect due to real life situation. So if there are more then 1 distances for a given pair of points the distances are averaged. But due to the imprecise distances there can be a difficulty when determining the exact (relative) location of a point. So I want to average the different possible locations to the "optimal" one.
Can you help me going through my challenge step by step?
| 0 | 0 | 0 | 0 | 1 | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.