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'm trying to write a small 'perspective' javascript app that allows me to fly through a set of x,y,z points that inhabit a 3d space.
I have the concept of a camera which changes its rotation and xyz position, while each point maintains a constant xyz point.
I then have a set of equations that works out how the camera's x,y,z coordinates should be adjusted for flying directly forwards. The x,y,z adjustments obviously depend upon the rotation of the camera.
It almost works, but at certain 'attitudes' the camera position adjustment goes wrong and the flightpath doesn't go straight ahead but goes off at an angle, or even reverses. The equations for working out the projection are as follows:
var directionFactor = 1;
if (direction == 'backward') directionFactor = -1;
sx = Math.sin(cameraView.rotX);
cx = Math.cos(cameraView.rotX);
sy = Math.sin(cameraView.rotY);
cy = Math.cos(cameraView.rotY);
sz = Math.sin(cameraView.rotZ);
cz = Math.cos(cameraView.rotZ);
// Z-Axis
ztrig = Math.sqrt((cx * cx) + (cy * cy)) * (cx * cy);
cameraView.z = cameraView.z + directionFactor *
(Math.abs(airspeed / 15) * ztrig);
// Y-Axis
ytrig = Math.sqrt((sx * sx) + (cz * cz)) * (sx * cz);
cameraView.y = cameraView.y + directionFactor *
(Math.abs(airspeed / 15) *ytrig);
// X-Axis
xtrig = Math.sqrt((cz * cz) + (sy * sy)) * (cz * sy);
cameraView.x = cameraView.x - directionFactor *
(Math.abs(airspeed / 15) * xtrig);
Obviously my equations aren't quite right. Can anyone tell me where I'm going wrong? Much appreciated and thanks.
| 0 | 0 | 0 | 0 | 1 | 0 |
I have an integer programming problem. I have a pipe, 10m long. I want to cut out as many 1.2meter pieces as I can and then cut the rest of the pipe in 100mm pieces. I have to leave 100mm for the machine to grab. How do I optimize this in mathematica? I can solve it as an equality i guess but if i just want the answer straight out.
Basically, as many y's as possible, then x:es.
Maximize[{x*100+y*1200, x*100+y*1200<9900},{x,y},Integers] just gives me an inequality plot.
And yes, I have checked instructions at wolfram.
| 0 | 0 | 0 | 0 | 1 | 0 |
I often see type declarations similar to this when looking at Haskell:
a -> (b -> c)
I understand that it describes a function that takes in something of type a and returns a new function that takes in something of type b and returns something of type c. I also understand that types are associative (edit: I was wrong about this - see the comments below), so the above could be rewritten like this to get the same result:
(a -> b) -> c
This would describe a function that takes in something of type a and something of type b and returns something of type c.
I've also heard that you can make a complement (edit: really, the word I was looking for here is dual - see the comments below) to the function by switching the arrows:
a <- b <- c
which I think is equivalent to
c -> b -> a
but I'm not sure.
My question is, what is the name of this kind of math? I'd like to learn more about it so I can use it to help me write better programs. I'm interested in learning things like what a complimentary function is, and what other transformations can be performed on type declarations.
Thanks!
| 0 | 0 | 0 | 0 | 1 | 0 |
I am creating an iphone app with objective-c. I have a math problem I need help on. I am new at this so I need to keep it simple. Any sample code would be appreciated.
This is the problem I want to display
person A (UItext input ) earns $x a day(UIText input) and keeps a total $y(UILabel).
person b (UItext input ) earns $x a day(UIText input) and keeps a total $y.
person c (UItext input ) earns $x a day(UIText input) and keeps a total $y.
Grand Total= $z
I can not figure out how I store total , retrieve it, then update the total value.
| 0 | 0 | 0 | 0 | 1 | 0 |
I need to perform some atomic arithmetic in Rails but the only way I've found to do it for single objects is via the crude update_all class method, e.g.:
Account.update_all(["debits = debits + ?", amount], :id => id)
With collection associations, the update_all class method should be usable as an association method, since the collection will pass missing method calls on to the class with the relevant scope:
accounts.update_all(["debits = debits + ?", amount])
When dealing with collections, this is much nicer and less repetitive. However this doesn't work for singleton associations, i.e. belongs_to and has_one. The method_missing for AssociationProxy passes through to the target instance, which won't have an update_all instance method (naturally).
Is there a more elegant way to perform this arithmetic? Or is update_all as good as it gets?
| 0 | 0 | 0 | 0 | 1 | 0 |
How would you generate a very very large random number? I am thinking on the order of 2^10^9 (one billion bits). Any programming language -- I assume the solution would translate to other languages.
I would like a uniform distribution on [1,N].
My initial thoughts:
--You could randomly generate each digit and concatenate. Problem: even very good pseudorandom generators are likely to develop patterns with millions of digits, right?
You could perhaps help create large random numbers by raising random numbers to random exponents. Problem: you must make the math work so that the resulting number is still random, and you should be able to compute it in a reasonable amount of time (say, an hour).
If it helps, you could try to generate a possibly non-uniform distribution on a possibly smaller range (using the real numbers, for instance) and transform. Problem: this might be equally difficult.
Any ideas?
| 0 | 0 | 0 | 0 | 1 | 0 |
I am implementing Naive Bayes algorithm for text classification. I have ~1000 documents for training and 400 documents for testing. I think I've implemented training part correctly, but I am confused in testing part. Here is what I've done briefly:
In my training function:
vocabularySize= GetUniqueTermsInCollection();//get all unique terms in the entire collection
spamModelArray[vocabularySize];
nonspamModelArray[vocabularySize];
for each training_file{
class = GetClassLabel(); // 0 for spam or 1 = non-spam
document = GetDocumentID();
counterTotalTrainingDocs ++;
if(class == 0){
counterTotalSpamTrainingDocs++;
}
for each term in document{
freq = GetTermFrequency; // how many times this term appears in this document?
id = GetTermID; // unique id of the term
if(class = 0){ //SPAM
spamModelArray[id]+= freq;
totalNumberofSpamWords++; // total number of terms marked as spam in the training docs
}else{ // NON-SPAM
nonspamModelArray[id]+= freq;
totalNumberofNonSpamWords++; // total number of terms marked as non-spam in the training docs
}
}//for
for i in vocabularySize{
spamModelArray[i] = spamModelArray[i]/totalNumberofSpamWords;
nonspamModelArray[i] = nonspamModelArray[i]/totalNumberofNonSpamWords;
}//for
priorProb = counterTotalSpamTrainingDocs/counterTotalTrainingDocs;// calculate prior probability of the spam documents
}
I think I understood and implemented training part correctly, but I am not sure I could implemented testing part properly. In here, I am trying to go through each test document and I calculate logP(spam|d) and logP(non-spam|d) for each document. Then I compare these two quantities in order to determine the class (spam/non-spam).
In my testing function:
vocabularySize= GetUniqueTermsInCollection;//get all unique terms in the entire collection
for each testing_file:
document = getDocumentID;
logProbabilityofSpam = 0;
logProbabilityofNonSpam = 0;
for each term in document{
freq = GetTermFrequency; // how many times this term appears in this document?
id = GetTermID; // unique id of the term
// logP(w1w2.. wn) = C(wj)∗logP(wj)
logProbabilityofSpam+= freq*log(spamModelArray[id]);
logProbabilityofNonSpam+= freq*log(nonspamModelArray[id]);
}//for
// Now I am calculating the probability of being spam for this document
if (logProbabilityofNonSpam + log(1-priorProb) > logProbabilityofSpam +log(priorProb)) { // argmax[logP(i|ck) + logP(ck)]
newclass = 1; //not spam
}else{
newclass = 0; // spam
}
}//for
My problem is; I want to return the probability of each class instead of exact 1's and 0's (spam/non-spam). I want to see e.g. newclass = 0.8684212 so I can apply threshold later on. But I am confused here. How can I calculate the probability for each document? Can I use logProbabilities to calculate it?
| 0 | 0 | 0 | 1 | 0 | 0 |
I have an app which has common maths functions behind the scenes:
add(x, y)
multiply(x, y)
square(x)
The interface is a simple google- style text field. I want the user to be able to enter a plain text description -
'2*3'
'2 times 3'
'multiply 2 and 3'
'take the product of 2 and 3'
and get a answer mathematical answer
Question is, how should I map the text descriptions to the functions ? I'm guessing I need to
tokenise the text
identify key tokens (function names, arguments)
try and map token combinations to function signatures
However I'm guessing this is already a 'solved problem' in the machine learning space. Should I be using Natural Language Processing ? Plain text search ? Something else ?
All ideas gratefully received, plus implementation suggestions [I'm using Python/AppEngine; I know about NLTK and Whoosh]
[PS I understand Google does this already, at least for the first two queries on the list. I'm guessing they also go it statistically, having a very large amount of search data. I don't have a large amount of data available, so will need an alternative approach].
| 0 | 1 | 0 | 1 | 0 | 0 |
I have a tooltip that opens via javascript on mouseover. From the following values how can I determine if this tooltip is cut off from the top edge of the screen (in this case it is) :
top margin: 72.5 inner height: 607 offsettop: 75 offsetheight: 26
and here are values from a tooltip below it that is not cut off, and fits perfectly in the window:
top margin: 53.5 inner height: 607 offsettop: 209 offsetheight: 222
I want to be able to detect if the tooptip is cut off and then apply changes to the margin to push it down to fit in the screen.
| 0 | 0 | 0 | 0 | 1 | 0 |
This is over my head, can someone explain it to me better? http://mathworld.wolfram.com/Reflection.html
I'm making a 2d breakout fighting game, so I need the ball to be able to reflect when it hits a wall, paddle, or enemy (or a enemy hits it).
all their formula's are like: x_1^'-x_0=v-2(v·n^^)n^^.
And I can't fallow that. (What does ' mean or x_0? or ^^?)
| 0 | 0 | 0 | 0 | 1 | 0 |
We're currently developing a full-text-search-enabled app and we Lucene.NET is our weapon of choice. What's expected is that an app will be used by people from different countries, so Lucene.NET has to be able to search across Russian, English and other texts equally well.
Are there any universal and culture-independent stemmers and analyzers to suit our needs? I understand that eventually we'd have to use culture-specific ones, but we want to get up and running with this potentially quick and dirty approach.
| 0 | 1 | 0 | 0 | 0 | 0 |
Possible Duplicate:
working on a proj in neural network
Is it mandatory that neural network will only take binary values as an input?
| 0 | 1 | 0 | 1 | 0 | 0 |
I would like to keep trailing zeros, for example, if I type:
round(5.2, 3)
I would like the output to be:
5.200
| 0 | 0 | 0 | 0 | 1 | 0 |
Python: Clustering Search Engine Keywords
Hi,
I have a CSV, up to 20,000 rows (I have had 100,000+ for different websites), each row containing a referring keyword (i.e. a keyword someone typed into a search engine to find the website in question), and a number of visits.
What I'm looking to do is cluster these keywords into clusters of "similar meaning", and create a hierarchy of the clusters (structured in order of summed total number of searches per cluster).
An example cluster - "womens clothing" - would ideally contain keywords along these lines:
womens clothing, 1000
ladies wear, 300
womens clothes, 50
ladies clothing, 6
womens wear, 2
I could look to use something like the Python Natural Language Toolkit: http://www.nltk.org/ and WordNet, but, I'm guessing that for some websites the referring keywords will be words/phrases that WordNet knows nothing about. For example, if the website is a celebrity website WordNet is unlikely to know anything about "Lady Gaga", worse situation if the website is a news website.
So, I'm also guessing therefore that the solution has to be one that looks to use just the source data itself.
My query is very similar to the one raised at How to cluster search engine keywords?, only I'm looking for somewhere to start but using Python instead of Java.
I did also wonder whether Google Predict and/or Google Refine might be of any use.
Anyway, any thoughts/suggestions most welcome,
Thanks,
C
| 0 | 1 | 0 | 0 | 0 | 0 |
I write a lot of methods looking a bit like this:
/* myVal must be between 10 and 90 */
int myVal = foo;
if(myVal < 10) { myVal = 10; }
else if (myVal > 90) { myVal = 90; }
Is there a more elegant way of doing it? Obviously you could easily write a method, but I wondered if any languages had a more natural way of setting a constraint, or whether there was something else I'm missing.
Language agnostic, because I'm interested in how different languages might deal with it.
| 0 | 0 | 0 | 0 | 1 | 0 |
I have a set of coupled equations for the variables H, W, P, & T (below) that I need to non-dimensionalize. Is there a way of achieving this in Mathematica as doing it manually is proving difficult.
{(a 1/(1 + R T[t]) - b) H[t] - (ap + bp) P[t] - bt T[t] == H'[t],
L P[t] - g W[t] - B W[t] H[t] == W'[t],
B W[t] H[t] - (up + b + bp + bt T[t]/H[t]) P[t] -
bp (P[t]^2)/H[t] ((k + 1)/k) + phi T[t] == P'[t],
H[t] (theta) - (b + bp P[t]/H[t] + bt ) T[t] -
bt (T[t]^2)/H[t] ((k + 1)/k) - v P[t] == T'[t]}
Parameter units: a = /H/unit time; b = /H/unit time; B = /H/unit time; theta = T/H/unit time; ap = /P/unit time; bp = /P/unit time; up = /P/unit time; v = /P/unit time; L = W/P/unit time; R = /T/unit time; bt = /T/unit time; phi = /T/unit time; g = /W/unit time; k = constant.
| 0 | 0 | 0 | 0 | 1 | 0 |
I am making some calculations with PHP and I don't want a number to be above 100. So, for example I want 50 + 80 to be 100 and not 130. Basically cap any result to 100. How can I achieve this?
| 0 | 0 | 0 | 0 | 1 | 0 |
I want to get the opposite number of binary number (means x--> -(x) and -(x) --> x).
What will be the algorithm ? I thought about change all bits ("1" to "0" and "0" to "1") and add "1" to it. Is it OK ?
thnx
| 0 | 0 | 0 | 0 | 1 | 0 |
Simple question I hope.
If I have a set of data like this:
Classification attribute-1 attribute-2
Correct dog dog
Correct dog dog
Wrong dog cat
Correct cat cat
Wrong cat dog
Wrong cat dog
Then what is the information gain of attribute-2 relative to attribute-1?
I've computed the entropy of the whole data set: -(3/6)log2(3/6)-(3/6)log2(3/6)=1
Then I'm stuck! I think you need to calculate entropies of attribute-1 and attribute-2 too? Then use these three calculations in an information gain calculation?
Any help would be great,
Thank you :).
| 0 | 0 | 0 | 1 | 0 | 0 |
Hy
How do i show the following:
f(n) <= f(n-1) + f(n-2)+ .. + f(1) implies f(n) = O(2^n)
I think we can assume that f is monotonically increasing =>
f(n) <= n*f(n-1)
| 0 | 0 | 0 | 0 | 1 | 0 |
I am currently working on a project (TSP) and am attempting to convert some simulated annealing pseudocode into Java. I have been successful in the past at converting pseudocode into Java code, however I am unable to convert this successfully.
The pseudocode is:
T0(T and a lowercase 0) Starting temperature
Iter Number of iterations
λ The cooling rate
1. Set T = T0 (T and a lowercase 0)
2. Let x = a random solution
3. For i = 0 to Iter-1
4. Let f = fitness of x
5. Make a small change to x to make x’
6. Let f’ = fitness of new point
7. If f’ is worse than f then
8. Let p = PR(f’, f, Ti (T with a lowercase i))
9. If p > UR(0,1) then
10. Undo change (x and f)
11. Else
12. Let x = x’
13. End if
14. Let Ti(T with a lowercase i) + 1 = λTi(λ and T with a lowercase i)
15. End for
Output: The solution x
If somebody could show me a basic mark-up of this in Java I would be extremely grateful - I just can't seem to figure it out!
I am working across multiple classes using a number of functions (which I will not list as it is irrelevant for what I am asking). I already have a smallChange() method and a fitness function - could there be a chance that I would need to create a number of different versions of said methods? For example, I have something like:
public static ArrayList<Integer> smallChange(ArrayList<Integer> solution){
//Code is here.
}
Could I possibly need another version of this method which accepts different parameters? Something along the lines of:
public static double smallChange(double d){
//Code is here.
}
All I require is a basic idea of how this would look when written in Java - I will be able to adapt it to my code once I know what it should look like in the correct syntax, but I cannot seem to get past this particular hurdle.
| 0 | 1 | 0 | 0 | 0 | 0 |
I know that to draw a regular polygon from a center point, you use something along the lines of:
for (int i = 0; i < n; i++) {
p.addPoint((int) (100 + 50 * Math.cos(i * 2 * Math.PI / n)),
(int) (100 + 50 * Math.sin(i * 2 * Math.PI / n))
);
}
However, is there anyway to change this code (without adding rotations ) to make sure that the polygon is always drawn so that the topmost or bottommost edge is parallel to a 180 degree line? For example, normally, the code above for a pentagon or a square (where n = 5 and 4 respectively) would produce something like:
When what I'm looking for is:
Is there any mathematical way to make this happen?
| 0 | 0 | 0 | 0 | 1 | 0 |
I'm a beginner programmer, starting in Python. I'm attempting to use math.log10(x) in my program, but keep getting the error "NameError: name 'math' is not defined".
The intellisense pops up while I'm typing, so it seems like I should be able to use it. The guides I've read so far have said little about how to properly pull up a module, so I'm kind of lost.
Here's my current program:
print("Enter an integer 'n' that is greater than 1: ")
n = int(input())
Primes = [2]
#List of Prime Numbers
Candidate = 3
#Number tested for Primeness
Product = 1
#Running product of prime numbers < n
Logarithm = True
#Will be the log of the product of the primes
##Ratio = True
## #Will be the ratio of the Logarithm to n
while Primes[len(Primes)-1] <= n:
#Continue only while Primes < n
IsPrime = True
i=0
while i < len(Primes):
if Candidate%Primes[i] == 0:
IsPrime = False
else:
Product = Product * Candidate
#Multiplies the current product by the newest prime < n
i = i + 1
if IsPrime:
Primes.append(Candidate)
#Adds newest prime to the list
Candidate = Candidate + 1
Logarithm = math.log10(Product)
I know this is a very entry level question, but I could use the help. Thank you!
| 0 | 0 | 0 | 0 | 1 | 0 |
this is my code:
from math import ceil
a = 25
a = float(a/10)
a = int(ceil(a))*10
print a
i get 20, but i want get 30 ,
the next is what i want get:
if the a is 22 , i want get 20
if the a is 25 , i want get 30
if the a is 27 , i want get 30
if the a is 21 , i want get 20
so what can i do ,
thanks
| 0 | 0 | 0 | 0 | 1 | 0 |
I am trying to figure out how getRotationMatrix() and getOrientation() work exactly.
So far I've known that in getRotationMatrix() function it crossproducts the gravity vector with the magnetic vector to get the new vector pointing to the East. And then , it crossproducts the East vector with the gravity vector again to get the vector pointing to the magnetic north. According to this article said, now we have three orthogonal vectors and we can form a rotation matrix.
Here is my first question: Why we should crossproduct the East vector with gravity vector again to get a vector pointing the magnetic north? Isn't the original magnetic vector pointing the magnetic north? what are the difference between new vector and the original magnetic vector?
Speaking about the getOrientation(), here is my second question: how do the azimuth, roll and pitch come out? Are there any equations or formula for explanation?
you can go to this website to see the code
very appreciated for your attention. Thanks a lot!
| 0 | 0 | 0 | 0 | 1 | 0 |
For a given array of integers, find the maximum distance between 2 points (i and j) that have higher values than any element between them.
Example:
values: 0 10 8 9 6 7 4 10 0
index : 0 1 2 3 4 5 6 7 8
for the values above the solution is i=1, j=7, but
if the value of index 7 is 9 instead of 10 the solution is i=3, j=7
if the value of index 7 is 7 instead of 10 the solution is i=5, j=7
I can't see a solution in O(n) ... anyone ?
| 0 | 0 | 0 | 0 | 1 | 0 |
So basically when I try to draw more a mesh inside an FBX file its orientation is always removed and it's scaled down. I'm not sure if the issue is caused by code or the way I'm exporting the FBX files. I have been trying to narrow down the cause and I am fairly sure it's not caused by the way I export the FBX (but I could be wrong), so it's either the XNA content pipeline or my drawing code
Here are some pics I took to show my problem, where the gray background is in 3Ds Max as I see it and red background is in XNA:
THis is as it appears in 3D StudioMax: http://i.stack.imgur.com/e0oW4.png
This is how it appears in XNA: http://i.stack.imgur.com/1vOcx.png
Both are being viewed from the same angle and direction but varying distances.
Now what is really odd is if I create another mesh in max, say a box, and export that (along with the original model), it works fine: http://i.stack.imgur.com/SIDg9.png
So long as there is more than one mesh in the fbx model it draws properly (though I'm still suspicious if it's drawing with proper scaling applied, i.e. if in Max it is 1 unit long in XNA it becomes something like 1.27 units long), if there is less its orientation which I applied to it in 3D studio max is removed when I draw it.
This is how I draw the model:
model.CopyAbsoluteBoneTransformsTo(boneTransforms);
foreach (ModelMesh mesh in model.Meshes)
{
foreach (BasicEffect effect in mesh.Effects)
{
effect.World = boneTransforms[mesh.ParentBone.Index];
Vector3 cameraPosition = Camera.Get.Position;// new Vector3(0, 0, 0);
//cameraPosition.X = -Camera.Get.PosX;
//cameraPosition.Y = Camera.Get.PosY;
effect.View = Camera.Get.View;// Matrix.CreateLookAt(cameraPosition, cameraPosition + Camera.Get.LookDir, Camera.Get.Up);
effect.Projection = Matrix.CreatePerspectiveFieldOfView(MathHelper.PiOver4,
BaseGame.Get.GraphicsDevice.Viewport.AspectRatio,
0.01f, 1000000); //Matrix.CreateOrthographic(800 / 1, 480 / 1, 0, 1000000);
//effect.TextureEnabled = true;
effect.LightingEnabled = true;
effect.PreferPerPixelLighting = true;
//effect.SpecularColor = new Vector3(1, 0, 0);
}
mesh.Draw();
}
Obviously mesh.draw() is called twice when there is more than one mesh in the fbx file..
| 0 | 0 | 0 | 0 | 1 | 0 |
I want to solve a matrix with PHP. For example, if I have three points: (x0, y0), (x1, y1) and (x2, y2), I want to know what p[0], p[1] and p[2] is in y = p[2]*x^2 + p[1]*x^1 + p[0]*x^0, valid for all those points. If n points are given, I want to solve y = p[n] * x^n + p[n-1] * x^(n-1) + ... + p[0] * x^0. What I have at this point, is this:
<?php
$system = new EQ();
$system->add(1, 2);
$system->add(4, 5);
$system->solvePn(0);
class EQ {
private $points = array();
public function add($x, $y) {
$this->points[] = array($x, $y);
}
public function solvePn($n) {
// Solve p[n]
// So eliminate p[m], p[m-1], ..., p[n+1], p[n-1], ..., p[1], p[0]
$m = count($this->points);
$a = $m;
// Eliminate p[a]
if ($a != $n) {
}
$a--;
}
}
?>
But now I don't know what to do next.
| 0 | 0 | 0 | 0 | 1 | 0 |
I want to redo my mathematics, since I honestly feel deprived. I'm a pre-final year Computer Engg (!) student in India. I eventually want to be a mathematically mature (yeah, that's how I wanna phrase it!) PROGRAMMER (in Machine Learning, NLP)! A Genuine request.
An example of kind of maturity I expect will be clear by following example:
Someone asks me to write a C program to calculate the sum of the squares of the first 100 odd natural numbers. Naturally my answer would go something like:
for(i=0,sum=0;i<100;i++)
{
sum += square(2*i+1);
}
BUT, one of my 'mathematically mature' friend came up with this (yeah this thing was actually asked!)
∑(2n+1)² = ∑ (4n² + 4n + 1)= ...SO ON.
Came up with a formula & put 100 for n & he was done in a single C line.
I couldn't think of such a thing, until he did. So, I think I've made things a little simpler for you to get my intention of asking this question.
| 0 | 1 | 0 | 0 | 1 | 0 |
I have an issue related to an ecommerce shopping cart. In certain circumstances (usually involving special offers or vouchers) a reduction might be made to the overall cart total - e.g. £10 voucher off total cart price. To calculate the tax part of this cart one of the suggestions by the tax office in the UK is to divide the reduction by the number of products in your cart and use this to calculate a new Gross (inc. tax) price for each product, from which you can calculate a new Net (excl. tax) price. For example: a £10 discount would be (in the case of 2 prods) £5 off gross of each. Obviously one problem here could be if one of the items is very cheap, e.g. £2.99 and therefore cannot take the £5 reduction.
I need a method of calculating what this reduction should be, so it splits evenly between the total number of products but never makes the cost of a single item less than zero. Help!
FWIW i will be programming this in PHP
EDIT
Oswald's example would give me something like this in PHP:
$prodA = 2.99;
$prodB = 20.00;
$total = ($prodA + $prodB);
$reduction = 5.00;
$newA = ($prodA - (($prodA/$total) * $reduction));
$newB = ($prodB - (($prodB/$total) * $reduction));
It seems to add up..
| 0 | 0 | 0 | 0 | 1 | 0 |
Okay, so say I got a rectangle (This is all 2d) made from Thing A's x,y,width and height. How would I calculate it's normal?
| 0 | 0 | 0 | 0 | 1 | 0 |
I have a List of 2D points. What's an efficient way of iterating through the points in order to determine whether the list of points are in a straight line, or curved (and to what degree). I'd like to avoid simply getting slopes between smaller subsets. How would I go about doing this?
Thanks for any help
Edit: Thanks for the response. To clarify, I don't need it to be numerically accurate, but I'd like to determine if the user has created a curved shape with their mouse and, if so, how sharp the curve is. The values are not too important, as long as it's possible to determine the difference between a sharp curve and a slightly softer one.
| 0 | 0 | 0 | 0 | 1 | 0 |
i have to solve the following formulation in matlab:
i am looking for the beta value, given is a vector full of wavelet coefficients x =(x_1,..,x_L)! How to solve this function in matlab? Can i use fzero?
edit: at the moment i tried this:
syms beta
x = [-1; 2; 3; 4; 5]
exp1 = sum((abs(x).^beta).* log(x)) /sum(abs(x).^beta)
exp2 = log(beta/size(x)*sum(abs(x).^beta))/beta
exp3 = (exp(-t)*t^((1/beta)-1))/int(exp(-t)*t^((1/beta)-1),0,inf)
fzero(exp1-exp2-exp3-1,1)
but still errors..
| 0 | 0 | 0 | 0 | 1 | 0 |
Hello fellow Number crunchers
As the headline suggests, I am looking for a library for learning and inference of Bayesian Networks. I have already found some, but I am hoping for a recommendation.
Requirements in a quick overview:
preferably written in Java or Python
configuration (also of the network itself) is a) possible and b) possible via code (and not solely via a GUI).
source code available
project is still maintained
the more powerful, the better
Which one do you recommend ?
| 0 | 0 | 0 | 1 | 0 | 0 |
Let's say I have two players: Player A and Player B and they have preferences over what resources (let's just be general and use the term 'resource'). Their preferences could be:
{p} {q} {p,q} {}
A 10 15 20 0
B 5 5 10 1
This says that the two players can have one resource, both or none. The greater the number the more the player wants it.
I believe the 'utilitarian' view would be to maximise the allocation overall so this would be the following two allocations:
A: {p,q} and
B: {}
because it adds to 21 even though B is not very happy [happiness 1 :-( ].
My question is what would the egalitarian (see wiki: 1) allocations be (if there are any)? I'm not sure how this would be properly calculated from the above table?
Thanks :).
| 0 | 1 | 0 | 0 | 0 | 0 |
Okay, so my paddle collision is working fine:
if(velo.y > 0){
float t = ((position.y - radius) - paddle.position.y)/ velo.y;
float ballHitX = position.x + velo.x * t;
if(t <= 1.0){
if(ballHitX >= paddle.position.x && ballHitX <= paddle.position.x + paddle.width){
velo.y = -velo.y;
}
}
}
But my wall collision isn't. (the ball goes up when under the paddle, and down when not)
if(velo.y < 0){
float t = ((position.y - radius) - (wall[2].y + wall[2].height))/ velo.y;
if(t <= 1.0){
velo.y = -velo.y;
}
}
How do I stop this error and make it so the ball bounces off the wall?
| 0 | 0 | 0 | 0 | 1 | 0 |
1,4,13,40,121...((3 * n) + 1) works slightly more efficiently than 1,2,4,8,16...(2 * n) when inserting random numbers to a sorting algorithm.
Why is this? Is it anything to do with threading?
Thanks.
| 0 | 0 | 0 | 0 | 1 | 0 |
Some high school math concept has been forgotten, so I ask here.
If I have two points p1(x1,y1), p2(x2,y2), the direction is P1-->p2, that's p1 points to p2. To represent this direction by vector, is it Vector(x2-x1,y2-y1) or Vector(x1-x2, y1-y2)?
By the way, what is the purpose to normalize a vector?
| 0 | 0 | 0 | 0 | 1 | 0 |
What is the best way to add/subtract units to/from specific timestamp with respect to time zone in Erlang?
From what I've found, calendar of stdlib can work with either local or UTC time zone, no more. Moreover, arithmetics is recommended to do in UTC time zone only (the reason is obvious).
What should I do if, for instance, I need to add 1 month to {{2011,3,24},{11,13,15}} in, let's say, CET (Central European Time) and local (system) time zone is not CET? That is not even the same as converting this timestamp to UTC, adding 31 * 24 * 60 * 60 seconds and converting back to CET (that will give {{2011,4,24},{12,13,15}} instead of {{2011,4,24},{11,13,15}}). By the way we can't do even such a thing if CET is not local time zone with stdlib.
The answers I found googling are:
setenv to make local time zone = needed time zone (that is very ugly first of all; then it will only allow to convert needed time zone to utc and do arithmetics respective to utc, not the needed time zone)
open_port to linux date util and do arithmetics there (not that ugly; rather slow; needs some parsing, because the protocol between erlang and date will be textual)
port driver or erl_interface to C using its standard library (not ugly at all; but I didn't find ready to use solution and I'm not that good at C to write one)
The ideal solution would be something written in Erlang using OS timezone info, but I didn't find any.
Now I'm stuck to solution 2 (open_port to date util). Is there a better way?
Thanks in advance.
P. S. There was a similar issue, but no good answer there Time zone list issue
| 0 | 0 | 0 | 0 | 1 | 0 |
Here is a question for the Excel / math-wizards.
I'm having trouble doing a calculation which is based on a formula with a circular reference. The calculation has been done in an Excel worksheet.
I've deducted the following equations from an Excel file:
a = 240000
b = 1400 + c + 850 + 2995
c = CEIL( ( a + b ) * 0.015, 100 )
After the iterations the total of A+B is supposed to be 249045 (where b = 9045).
In the Excel file this gives a circular reference, which is set to be allowed to iterate 4 times.
My problem: Recreate the calculation in AS2, going through 4 iterations.
I am not good enough at math to break this problem down.
Can anyone out there help me?
Edit: I've changed the formatting of the number in variable a. Sorry, I'm from DK and we use period as a thousand separator. I've removed it to avoid confusion :-)
2nd edit: The third equation, C uses Excels CEIL() function to round the number to nearest hundredth.
| 0 | 0 | 0 | 0 | 1 | 0 |
I'm building a particles systems, one of the features I'd like to add is a "target" feature. What I want to be able to do is set an X,Y target for each particle and make it go there, not in a straight line though (duh), but considering all other motion effects being applied on the particle.
The relevant parameters my particles have:
posx, posy : inits with arbitrary values. On each tick speedx and speedy are added to posx and posy respectively
speedx, speedy : inits with arbitrary values. On each tick accelx and accely are added to speedx speedy respectively if any)
accelx, accely : inits with arbitrary values. With current implementation stays constant through the lifespan of the particle.
life : starts with an arbitrary value, and 1 is reduced with each tick of the system.
What I want to achieve is the particle reaching the target X,Y on it's last life tick, while starting with it's original values (speeds and accelerations) so the motion towards the target will look "smooth". I was thinking of accelerating it in the direction of the target, while recalculating the needed acceleration force on each tick. That doesn't feel right though, would love to hear some suggestions.
| 0 | 0 | 0 | 0 | 1 | 0 |
I am writing a CKY parser for a Range Concatenation Grammar. I want to use a treebank as grammar, so the grammar will be large. I've written a prototype 1 in Python and it seems to work well when I simulate a treebank of a couple tens of sentences, but the memory usage is unacceptable. I tried writing it in C++ but so far that has been very frustrating as I have never used C++ before. Here's some data (n is number of sentences the grammar is based on):
n mem
9 173M
18 486M
36 836M
This growth pattern is what is to be expected given the best-first algorithm, but the amount of overhead is what concerns me. The memory usage according to heapy is a factor ten smaller than these numbers, valgrind reported something similar. What causes this discrepancy and is there anything I can do about it in Python (or Cython)? Perhaps it's due to fragmentation? Or maybe it is the overhead of python dictionaries?
Some background: the two important datastructures are the agenda mapping edges to probabilities, and the chart, which is a dictionary mapping nonterminals and positions to edges. The agenda is implemented with a heapdict (which internally uses a dict and a heapq list), the chart with a dictionary mapping nonterminals and positions to edges. The agenda is frequently inserted and removed from, the chart only gets insertions and lookups. I represent edges with tuples like this:
(("S", 111), ("NP", 010), ("VP", 100, 001))
The strings are the nonterminal labels from the grammar, the positions are encoded as a bitmask. There can be multiple positions when a constituent is discontinuous. So this edge could be represent an analysis of "is Mary happy", where "is" and happy" both belong to the VP. The chart dictionary is indexed by the first element of this edge, ("S", 111) in this case. In a new version I tried transposing this representation in the hope that it would save memory due to reuse:
(("S", "NP", "VP), (111, 100, 011))
I figured that Python would store the first part only once if it would occur in combination with different positions, although I'm not actually sure this is true. In either case, it didn't seem to make any difference.
So basically what I am wondering is if it is worth pursuing my Python implementation any further, including doing things with Cython and different datastructures, or that writing it from the ground up in C++ is the only viable option.
UPDATE: After some improvements I no longer have issues with memory usage. I'm working on an optimized Cython version. I'll award the bounty to the most useful suggestion for increasing efficiency of the code. There is an annotated version at http://student.science.uva.nl/~acranenb/plcfrs_cython.html
1 https://github.com/andreasvc/disco-dop/
-- run test.py to parse some sentences. Requires python 2.6, nltk and heapdict
| 0 | 1 | 0 | 0 | 0 | 0 |
A is a list of increasing fixed values (frequencies). It doesn't step evenly but the values never change.
A = 5, 10, 17, 23, 30
Each value in A is weighted by the corresponding value in list B (volume).
B = 2.2, 3.5, 4.4, 3.2, 1.1
I want to calculate the loudest frequency (A). The problem is that the loudest frequency may be 14 but I can't tell from this data set. How can I calculate, based on list B, what the loudest frequency might be in list A?
| 0 | 0 | 0 | 0 | 1 | 0 |
I have a situation whereby a series of 15 dates have been created, currently in UNIX timestamps.
Another variable <?php $dateidate = date(strtotime('+20 days')); ?>
The objective is to find the smallest of the 15 other dates that is greater > than $dateidate and display in the format of 'd-m-Y'
Once we've done that is there a way to get the second smallest of the 15 other dates that is greater > than $dateidate and display in the format of 'd-m-Y'.
| 0 | 0 | 0 | 0 | 1 | 0 |
I am looking for a way to simplify algebraic expressions in VB.NET. It is preferred if you can give me a link to a pre-written library or class, but pointers on how to write one are also appreciated.
| 0 | 0 | 0 | 0 | 1 | 0 |
How do I calculate the amount of "steps" there is from one field to another in a grid, moving orthogonally?
I am implementing an A* pathfinding system for a game that I am developing, and this simple mathematical operation is in my way.
I should probably re-attend third grade. Haha.
| 0 | 0 | 0 | 0 | 1 | 0 |
temperature decrease_capacity
---------- ----------------
125 5
150 10
175 15
etc...
if i want to select decrease_capacity for temperature=166, how i will get.
| 0 | 0 | 0 | 0 | 1 | 0 |
Can anyone explain how the line of sight works in 2d? Which will be really help full for my 2d experiments. The experiment am working is a simple 2d simulation. Player move in the world from one place to other , my world exactly looks like this. I did the character movement successfully from one way point to other (A to G) , my goal is - when the character passes each point it has to perform some search in that area before it leaves to next point. To achieve I felt way point is better solution , can anyone help me on this.Thanks!
Edit :
As soon as the player enters a room/checkpoint I will take user to next scene like this
where the pickups are place some where on the canvas and my player have to collect them all and leave the area - Back to Map scene.
| 0 | 1 | 0 | 0 | 0 | 0 |
My program needs to calculate x in the formula a^x = b, where I know the values of a and b.
So for instance, if:
a=3 and b=9, the answer would be 2.
a=3 and b=27, the answer is 3.
What if a=2 and b=5?
I could write my own iterative algorithm, but is there a built-in function, or some simple combination of built-in functions?
| 0 | 0 | 0 | 0 | 1 | 0 |
I have a table as follows:
product | quantity | price | gift | giftprice
--------|----------|-------|------|----------
1 | 2 | 9.99 | 0 | 4.99
2 | 3 | 3.50 | 1 | 2.25
3 | 1 | 4.75 | 1 | 1.50
What I'd like to have an SQL query that will give me a figure that gives me the sum of all the records with quantity multiplied by price with the giftprice being added to the price before multiplication only if the 'gift' field is set to 1.
Pseudocode
foreach(record){
if(gift == 1){ linetotal = (price + giftprice) * quantity; }
else { linetotal = price * quantity; }
total = total + linetotal;
}
| 0 | 0 | 0 | 0 | 1 | 0 |
I am working in a grid-universe - objects only exist at integer locations in a 2 dimensional matrix.
Some terms:
Square - a discrete location. Each square has an int x and int y coordinate, and no two squares have the same x and y pair.
Adjacent: A square X is adjacent to another square Y if the magnitude of the difference in either their x or y coordinate is no greater than 1. Put more simply, all squares immediately in the N, NE, E, SE, S, SW, W, and NW directions are adjacent.
Legend:
'?' - Unknown Traversibility
'X' - Non Traversable Square
'O' - Building (Non Traversable)
' ' - Traversable Square
The problem:
Given the following generic situation:
? ? ? ? ? ? ? ?
? ? ? ? ? ? ? ?
? ? ? ? ? ? ? ?
? ? ? O O ? ? ?
? ? ? O O ? ? ?
? ? ? ? ? ? ? ?
? ? ? ? ? ? ? ?
? ? ? ? ? ? ? ?
where the builder is adjacent to one of the four buildings, I want to build two buildings such that they both share a common adjacent square that is also adjacent to at least one of the four existing buildings, and this common adjacent square is not blocked in.
Basic Valid solutions:
X X X X X X X X X X X X X X X X X X X X X X
X X X X X X X X X X X X X X X X X X X X X X
X X X X X X X X X X X X X X X X X X X X X X
X X X O O X X X X X X O O X X X X X X O O X X X
X X X O O X X X X X X O O X X X X X O O O X X X
X X X O X X X O X X X X
O O X X X O X X X X X X X X
X X X X X X X X X X X
Currently, I iterate through all traversable square adjacent to the four buildings, and look for squares that have 3 adjacent traversable squares, but this sometimes produces situations such as:
X X X X X X X X X X X X X X X X X X X X X X X X
X X X X X X X X X X X X X X X X X X X X X X X
X X X X X X X X X X O X X X X X O X
X X X O O X X X X X O O O X X X O O O X X
X X X O O X X X X X O O X X X X O O X X
X X X X X X X X X X X X X X
X X X O O X X X X X X X X X X X X X X X
X X X X X X X X X X X X X X X X X X
Any thoughts on how I can refine my algorithm?
EDIT: Added another failing case.
EDIT: I'd also like to be able to know if there isn't a possible configuration in which these conditions could be met. I'm not guaranteed a viable solution, and would like to not-try if there isn't a way to do this successfully.
| 0 | 1 | 0 | 0 | 0 | 0 |
I tried google and found little that I could understand.
I understand Markov chains to a very basic level: It's a mathematical model that only depends on previous input to change states..so sort of a FSM with weighted random chances instead of different criteria?
I've heard that you can use them to generate semi-intelligent nonsense, given sentences of existing words to use as a dictionary of kinds.
I can't think of search terms to find this, so can anyone link me or explain how I could produce something that gives a semi-intelligent answer? (if you asked it about pie, it would not start going on about the vietnam war it had heard about)
I plan on:
Having this bot idle in IRC channels for a bit
Strip any usernames out of the string and store as sentences or whatever
Over time, use this as the basis for the above.
| 0 | 1 | 0 | 0 | 0 | 0 |
I would like to code bayesian networks in java to understand them better, and I have found some code of Artificial Intelligence A Modern Approach (3rd Edition), "AIMA"
Do you recommend I read the code there and adapt to a particular problem, or how do I start?
Could you please orient me where in how to use the code?
I found google has it here and here ,
| 0 | 1 | 0 | 0 | 0 | 0 |
I am trying to solve a simple classification problem.
The Problem:
I have a set of text and I have to categorize them based on the content.
Solution using Mahout:
I understood that I have to convert the input to a sequence file to generate the model. Yes, I was able to do this. Now, how do I categorize my test data? The 20News example only tests for correctness. But, I want to do the actual classification.
I am not sure if I need to write code or use some existing classes available to classify the test set.?
| 0 | 0 | 0 | 1 | 0 | 0 |
I am writing a program that does some unit conversions from a Brix scale to some other units.
The program works by displaying a scale to the user, and allows the user to click on the scale to select a Brix measurement. The range I am using is between 1 & 30.
The problem is, the scale is not linear. As the Brix number gets higher, more space is between each increment, so I need to figure out the linear equation that would allow me to translate the y position of the user input to the number on the scale.
I made the following chart to show the correlation between the brix value and the y-position of the user click (in pixels):
Brix | PosY
=====|=====
0 | 0
1 | 10
5 | 50
10 | 100
12 | 123
15 | 155
16 | 167
19 | 201
21 | 225
24 | 262
26 | 287
28 | 314
30 | 340
Basically, I need to be able to figure out Brix, given PosY. How do I determine the equation to use?
| 0 | 0 | 0 | 0 | 1 | 0 |
What is the easiest way to get a list of whole factor pairs of a given integer?
For example: f(20) would return [(1,20), (2,10), (4,5)].
| 0 | 0 | 0 | 0 | 1 | 0 |
I need to do an experiment and I am new in NLP. I have read books that explain the theoritical issues but when it comes to practical I found it hard to find a guide. so please who knows anything in NLP especially the practical issues tell me and point me to the right path because I feel I am lost (useful books, useful tools and useful websites)
what I am trying to do is to take a text and find specific words for example animals such as dogs, cats,...etc in it then I need to extract this word and 2 words on each side.
For example
I was watching TV with my lovely cat last night.
the extracted text will be
(my lovely cat last night)
This will be my training example to the machine tool
Q1: there will be around 100 training examples similar to what I explained above. I used tocknizer to extracts words but how can I extract specific words(for our example all types of animals) with 2 words on each side. do I need to use tags for example or what is your idea?
Q2: If I have these training examples how can I prepare appropriate datasets that I can give it to the machine tool to train it? what should I write in this dataset to specify the animal and should I need to give other features? and how can I arrange it in a dataset .
many words from you might help me a lot please do not hesitate to tell what you know
| 0 | 1 | 0 | 0 | 0 | 0 |
In the form f(x,y,z) where x is a given integer sum, y is the minimum length of the sequence, and z is the maximum length of the sequence. But for now let's pretend we're dealing with a sequence of a fixed length, because it will take me a long time to write the question otherwise.
So our function is f(x,r) where x is a given integer sum and r is the length of a sequence in the list of possible sequences.
For x = 10, and r = 2, these are the possible combinations:
1 + 9
2 + 8
3 + 7
4 + 6
5 + 5
Let's store that in Python as a list of pairs:
[(1,9), (2,8), (3,7), (4,6), (5,5)]
So usage looks like:
>>> f(10,2)
[(1,9), (2,8), (3,7), (4,6), (5,5)]
Back to the original question, where a sequence is return for each length in the range (y,x). I the form f(x,y,z), defined earlier, and leaving out sequences of length 1 (where y-z == 0), this would look like:
>>> f(10,1,3)
[{1: [(1,9), (2,8), (3,7), (4,6), (5,5)],
2: [(1,1,8), (1,2,7), (1,3,6) ... (2,4,4) ...],
3: [(1,1,1,7) ...]}]
So the output is a list of dictionaries where the value is a list of pairs. Not exactly optimal.
So my questions are:
Is there a library that handles this already?
If not, can someone help me write both of the functions I mentioned? (fixed sequence length first)?
Because of the huge gaps in my knowledge of fairly trivial math, could you ignore my approach to integer storage and use whatever structure the makes the most sense?
Sorry about all of these arithmetic questions today. Thanks!
| 0 | 0 | 0 | 0 | 1 | 0 |
I am using Latent semantic analysis for text similarity. I have 2 questions.
How to select K value for dimention reduction?
I read alot every where that LSI work for similary meaning words for example car and automobile. How is it possible??? What is the magic step I am missing here?
| 0 | 0 | 0 | 0 | 1 | 0 |
I would just like to ask for assistance to anyone on the logic, and much better sample code of formulating an image's outline.
To make it clearer, I'm talking about a transparent image. Say, I have a PNG image with a polygon shape in the middle, or much better a top view of an island. Now, I would like to trace the outlines and set a color on it. Like the Effect 'Stroke' in Adobe Photoshop.
I have accomplished that far, I've created a program that would trace the outlines. But my problem is, it's linear scanning. From left to right, then down, then left to right again. I'm sure you get the idea. I wanted the tracing to be flowing, like you would trace it manually. Like you with Trace a Circle.
The purpose is, for it to be used as a trigger area for hovering accurately a polygon. And also my problem is if there's two island for example.
I hope my query is clear. Any suggestions, samples are appreciated. But much better if it's in a c# code form or pseudo code with some explanations.
Thanks a lot in advance.
--
Addition:
Also, I would like (I guess I've forgotten to mention) to record the coordinates of the stroke in a sequential manner. So I could manipulate them later on. That is why I wanted to make the outlining logic in a flow manner. That is the algorithm i'm looking for specifically. Thanks a lot!
| 0 | 0 | 0 | 0 | 1 | 0 |
Okay, so I'm trying to display a tilemap, but my math seems to be off.
private void MapPanel_Paint(object sender, PaintEventArgs e)
{
Graphics g = e.Graphics;
GraphicsUnit units = GraphicsUnit.Pixel;
for (int i = 0; i < map.tiles.Length; i++)
{
for (int j = 0; j < map.tiles[i].Length; j++)
{
int tileXCoord = 0;
int tileYCoord = 0;
int tileSheetWidth = tileMap.Width / map.tileSize;
if (map.tiles[i][j] != 0)
{
tileXCoord = tileSheetWidth % map.tiles[i][j];
tileYCoord = tileSheetWidth / map.tiles[i][j];
}
Rectangle destRect = new Rectangle((i * map.tileSize) - hScrollValue, (j * map.tileSize) - vScrollValue, map.tileSize, map.tileSize);
g.DrawImage(tileMap, destRect, tileXCoord * map.tileSize, tileYCoord * map.tileSize, map.tileSize, map.tileSize, units);
}
}
}
Now I'm trying to get my map to use a "word wrapped" tile index
[0][1]
[2][3]
But it's not working, anyone know why?
| 0 | 0 | 0 | 0 | 1 | 0 |
This may be a math question more than a programming question, but we'll see.
I'm trying to build a simple javascript click tracker that one could add to any website, which will plot its data to a heat map.
The Problem
If I capture the x/y coordinates of a click event on a web page being displayed in a window measuring 1024x768, and try to map that onto a heat map being displayed at 1280x1024 (or any other size), there's a good possibility that the click won't display in the correct location.
If, for example, the content of the web page is centred within a 960px wide div, because the x,y coordinates captured measure from an origin at the top-left corner of the window, the coordinates don't match in physical space.
I could use the difference between the two screen sizes to create an origin in the centre of all screens and measure from there, but then I wind up with the same problem for any content that isn't positioned relative to the centre of the page.
Is there a way to develop a set of absolute coordinates of an element on the page, without knowing the size of the browser window or what's on the page?
I know I could bind the click to the DOM element. That's fine, and I'll probably go that route, but now that I've found this problem, I'm curious as to the possible solution.
| 0 | 0 | 0 | 0 | 1 | 0 |
I have a school project to build an AI for a 2D racing game in which it will compete with several other AIs.
We are given a black and white bitmap image of the racing track, we are allowed to choose basic stats for our car (handling, acceleration, max speed and brakes) after we receive the map. The AI connects to the game's server and gives to it several times a second numbers for the current acceleration and steering. The language I chose is C++, by the way.
The question is
What is the best strategy or algorithm (since I want to try and win)? I currently have in mind some ideas found on the net and one or two of my own, but I would like before I start to code that my perspective is one of the best.
What good books are there on that matter?
What sites should I refer to?
| 0 | 1 | 0 | 0 | 0 | 0 |
I'm an AI Student, previously I was thinking about something, every time we guys we see a movie, the next time we the movie, it's the same thing, so those who have a knowledge of AI, such as the graph theory and so on, do you think it is feasible to create a dynamic movie, that is the first time you see it, it follows a path in the graph, the next time you see it, it follows a different path and as a result, we get a different movies, do u think this is feasible ??
| 0 | 1 | 0 | 0 | 0 | 0 |
I'm current attending a course where we have to write an AI to play battleships, and we managed to put out a great working one, but our teacher is a smartass and I'd like to make a cheating AI, that reads the memory and looks where the opponent AI has placed the ships.
The UI is running in a separate thread, where it runs an observer pattern on the logic in the main thread. The positions of the ships is stored in a binary two-dimensional array where true represents a point on a ship (not which, just any ship).
Now the question is: Is it possible to read the memory of the two-dimensional array of enemyBoard somehow, when it is running in the same process and in the same thread?
| 0 | 1 | 0 | 0 | 0 | 0 |
I have the following differentiation, I need to implement it in C#:
W(t)=d/dt(log(A(t)))
Where A(t) is a array of double data.
How can I obtain the resulting W(t) array from the derivative above?
Thanks
edit:
public double[,] derivative()
{
dvdt = new double[envelope.GetLength(0), envelope.GetLength(1)];
int h = 1;
for (int j = 0; j < envelope.GetLength(0); j++)
{
for (int i = 0; i < envelope.GetLength(1)-1 ; i++)
{
dvdt[j, i] = (envelope[j, i + h] - envelope[j, i]) / (h);
}
}
return dvdt;
}
I found this library http://autodiff.codeplex.com/ but i cant understand how the sample code is working and how i can apply it to my problem eh
| 0 | 0 | 0 | 0 | 1 | 0 |
Hough Transform can be used to extract lines from images. It can also be used to extract curves - this is a little harder though because higher dimensional Hough transforms are resource consuming. I was wondering whether how one restricts the Hough transform to 2D voting space for a curve of order 3 i.e. x^{3}+ax^{2}+bx+c ?
Anyone know any good sites explaining this (can't seem to find any). Or an explanation here if there isn't one :).
| 0 | 0 | 0 | 0 | 1 | 0 |
I'm trying to figure out how to get the distance from two circles relative to the corners of their square container boxes. I need some help with the maths here.
How can I work out the number of pixels for the line marked with a question mark?
Appreciate the help as always.
| 0 | 0 | 0 | 0 | 1 | 0 |
Got an asynchronous stream of events, where each event has information like -
Agency (one of many Agencies possible to be served by my solution)
Agent (one of many Agents in an Agency)
Served-Entity (a person/organization served by 1 or more agencies)
Date+Time
Class-Data (tags from a fixed but large set of tags)
What I need to do is to --
Correlate an event based on Served-Entity, Date+Time and Class-Data, and create a consolidated new Event. Example:
Event #0021: { Agency='XYZ', Agent='ABC', Served-Entity='MMN', Date+Time='12-03-2011/11:03:37', Class-Date='missed-delivery,no-repeat,untracable,orphan' }
Event #0193: { Agency='KLM', Agent='DAY', Served-Entity='MMN', Date+Time='12-03-2011/12:32:21', Class-Date='missed-delivery,orphan,lost' }
Event #1217: { Agency='KLM', Agent='CARE', Served-Entity='MMN', Date+Time='12-03-2011/18:50:45', Class-Date='escalated' }
Here I find 3 events which are spaced out in time (more than 7hr separation), which are for the same Served-Entity (MMN), occur within a certain time window (say 24-hours), have matching or related Class-Data.
Finally create a consolidated (new) event which could represent an inference drawn.
Be able to create reports on a per Agency, per Agency, per Served-Entity basis, based on things like specific Class-Data tags (e.g. missed-delivery) over a certain period of time. This could be done using the original/input events, or the synthesized (inference) events.
While this is not a requirement today, but quite likely to appear in future, that the "tags" that appear in Class-Data could grow, without any human intervention. So not sure if this should then be treated as unstructured data.
Also not an immediate requirement, but in future there may be a need to identify trends / patterns of event occurrences (i.e. Event1 led to Event2 led to Event3).
The event arrival rate could be quite high... possibly thousands of events per minute. Maybe more. And, I need to archive the original/synthesized events for a period of time (a month or so).
My solution needs to be based on FOSS components (preferably). Some research done so far, points in the direction of CEP (Complex Event Processing), Bayesian-Networks/Classification, Predictive-Analytics.
Looking for some suggestions regarding approach to take. I'd prefer to take the path which meets most of my goals, with minimum difficulty/time, or to put another way, "learning AI" or "formal statistical methods" isn't my short-term goal :-)
| 0 | 0 | 0 | 1 | 0 | 0 |
I'm not the math uncle, but a real one told me this:
"use fixed point instead of floating
point to do multiplication, division,
summation, trigonometry and
integration"
So instead of using double or float data types, what shall I do? Does anyone have a handy snippet or link that shows the difference for non-math-uncles?
| 0 | 0 | 0 | 0 | 1 | 0 |
I am planning to attend a project oriented advanced summer workshop here in India on Natural Language Processing.
Before start of the workshop, I have to make a project preference out of the following four areas about which I have limited knowledge.
Machine Translation Develop an English-Indian language translation
system.
Parsing Build an Indian Language (IL) Parser.
Morphological Analysis Develop and test Morphological Analyzers for
Indian Languages.
Speech Spoken Dialog Systems, Emotion/Prosody Detection, Synthesis
and Conversion
I have taken a course in Artificial Intelligence where NLP was introduced and fundamental sub-topics like POS tagging(Transformation Based Learning), word prediction using N-grams, Hidden Markov Models, Viterbi Algorithm, Natural Language Parsing, Context Free Grammar, CKY Algorithm were covered.
I understand this is a slightly vague question and the choice would depend primarily on my interests, but would appreciate guidance on which area would be better in terms of the research scope, practical application, industry opportunities etc.
EDIT: Application of skills/experience acquired while working on the project, outside NLP would also be a factor in the decision.
| 0 | 1 | 0 | 1 | 0 | 0 |
public int CalcBrackets(int teamCount)
{
int positions = 1;
while (positions < teamCount)
positions *= 2;
return positions;
}
I want the smallest number that is a power of 2 and bigger or equal than teamCount. Is this really the best way to do it? It sure looks horrible :(
| 0 | 0 | 0 | 0 | 1 | 0 |
Do you know the name of a tool to do some tones from a set of examples, I recently heard it created a great classical song like Bach's.
| 0 | 1 | 0 | 0 | 0 | 0 |
Through much trial and error I found the following lines of python code,
for N in range(2**1,2**3):
print [(2**n % (3*2**(2*N - n))) % (2**N-1) for n in range(2*N+1)]
which produce the following output,
[1, 2, 1, 2, 1]
[1, 2, 4, 1, 4, 2, 1]
[1, 2, 4, 8, 1, 8, 4, 2, 1]
[1, 2, 4, 8, 16, 1, 16, 8, 4, 2, 1]
[1, 2, 4, 8, 16, 32, 1, 32, 16, 8, 4, 2, 1]
[1, 2, 4, 8, 16, 32, 64, 1, 64, 32, 16, 8, 4, 2, 1]
i.e. powers of 2 up to 2**(N-1), 1, and the powers of two reversed. This is exactly what I need for my problem (fft and wavelet related). However, I'm not quite sure why it works? The final modulo operation I understand, it provides the 1 in the middle of the series. The factor 3 in the first modulo operation is giving me headaches. Can anyone offer an explanation? Specifically, what is the relationship between my base, 2, and the factor, 3?
| 0 | 0 | 0 | 0 | 1 | 0 |
The C99 standard defines ldexp(double a, int exp) as a × 2exp and scalbn(double a, int exp) as a × FLT_RADIXexp
What's the difference between the two if I'm using IEEE-754 arithmetic (i.e. FLT_RADIX == 2)?
| 0 | 0 | 0 | 0 | 1 | 0 |
I originally had a function that uses pow(), and I noticed it was returning zero values every time. While debugging it, I found that this seems to be the source of the problem:
#include <math.h>
#include <stdio.h>
#include <string.h>
int foo(int n)
{
printf("%d is number passed in
", n);
double base = (double) n;
printf("%d is base
", base);
printf("%d is power
", pow(base ,2));
return (1/2 *( pow( (double) n, 2)));
}
If I call foo on any integer value (say, 8), the second printf statement prints zero every time. (And of course, the third one does as well). Shouldn't conversion of double to int be straightforward?
| 0 | 0 | 0 | 0 | 1 | 0 |
The idea is to overload an operator * so it can multiply two strings representing decimal value of a number. The operator is part of a bigger class but that is not important. The algorithm is the same as in elementary school :)
Here's my code:
Bignumber operator* (Bignumber x, Bignumber y ){
int i, j, transfer=0, tmp, s1, s2, k;
char add[1];
string sol;
string a, b;
Bignumber v1, v2;
a=x.GetValue();
b=y.GetValue();
a.insert(0,"0");
b.insert(0,"0");
for(i=a.length()-1; i>=0; i--){
s1 = (int) a[i]-48;
for(k=a.length()-i-1; k >0 ; k--){
sol+="0";
}
for(j=b.length()-1; j >=0; j--){
s2=(int) b[j]-48;
tmp=s1*s2+transfer;
if(tmp >= 10){
transfer=tmp/10;
tmp=tmp-(10*transfer);
}
itoa(tmp, add, 10);
sol.insert(0, add);
}
v1=sol;
v2=v1+v2;
sol.erase(0);
transfer=0;
}
return v2;
}
This works fine most of the time but for some random values it doesnt work properly. like for example for 128*28 it returns 4854 instead of 3584.
Any idea what might be the problem?
operators + and = are already overloaded for the class Bignumber and they work fine.
| 0 | 0 | 0 | 0 | 1 | 0 |
I am using the nlp parser stanord.
I want to extract some elements like nsubj and more from Collection tdl.
My code is:
TreebankLanguagePack tlp = new PennTreebankLanguagePack();
GrammaticalStructureFactory gsf = tlp.grammaticalStructureFactory();
GrammaticalStructure gs = gsf.newGrammaticalStructure(parse);
Collection tdl = gs.typedDependenciesCollapsed();
but my problem is I don't know how to compare the elements.that I get from the Collection.
Thanks a lot for helping!
| 0 | 1 | 0 | 0 | 0 | 0 |
I am using libsvm for binary classification.. I wanted to try grid.py , as it is said to improve results.. I ran this script for five files in separate terminals , and the script has been running for more than 12 hours..
this is the state of my 5 terminals now :
[root@localhost tools]# python grid.py sarts_nonarts_feat.txt>grid_arts.txt
Warning: empty z range [61.3997:61.3997], adjusting to [60.7857:62.0137]
line 2: warning: Cannot contour non grid data. Please use "set dgrid3d".
Warning: empty z range [61.3997:61.3997], adjusting to [60.7857:62.0137]
line 4: warning: Cannot contour non grid data. Please use "set dgrid3d".
[root@localhost tools]# python grid.py sgames_nongames_feat.txt>grid_games.txt
Warning: empty z range [64.5867:64.5867], adjusting to [63.9408:65.2326]
line 2: warning: Cannot contour non grid data. Please use "set dgrid3d".
Warning: empty z range [64.5867:64.5867], adjusting to [63.9408:65.2326]
line 4: warning: Cannot contour non grid data. Please use "set dgrid3d".
[root@localhost tools]# python grid.py sref_nonref_feat.txt>grid_ref.txt
Warning: empty z range [62.4602:62.4602], adjusting to [61.8356:63.0848]
line 2: warning: Cannot contour non grid data. Please use "set dgrid3d".
Warning: empty z range [62.4602:62.4602], adjusting to [61.8356:63.0848]
line 4: warning: Cannot contour non grid data. Please use "set dgrid3d".
[root@localhost tools]# python grid.py sbiz_nonbiz_feat.txt>grid_biz.txt
Warning: empty z range [67.9762:67.9762], adjusting to [67.2964:68.656]
line 2: warning: Cannot contour non grid data. Please use "set dgrid3d".
Warning: empty z range [67.9762:67.9762], adjusting to [67.2964:68.656]
line 4: warning: Cannot contour non grid data. Please use "set dgrid3d".
[root@localhost tools]# python grid.py snews_nonnews_feat.txt>grid_news.txt
Wrong input format at line 494
Traceback (most recent call last):
File "grid.py", line 223, in run
if rate is None: raise "get no rate"
TypeError: exceptions must be classes or instances, not str
I had redirected the outputs to files , but those files for now contain nothing..
And , the following files were created :
sbiz_nonbiz_feat.txt.out
sbiz_nonbiz_feat.txt.png
sarts_nonarts_feat.txt.out
sarts_nonarts_feat.txt.png
sgames_nongames_feat.txt.out
sgames_nongames_feat.txt.png
sref_nonref_feat.txt.out
sref_nonref_feat.txt.png
snews_nonnews_feat.txt.out (--> is empty )
There's just one line of information in .out files..
the ".png" files are some GNU PLOTS .
But i dont understand what the above GNUplots / warnings convey .. Should i re-run them ?
Can anyone please tell me on how much time this script might take if each input file contains about 144000 lines..
Thanks and regards
| 0 | 0 | 0 | 1 | 0 | 0 |
I'm using Physics for Games Programmers to develop a simple physics-based game.
I need to compute the resulting velocities for two spheres after an elastic collision. The book example for this in Chapter 6 assumes that the 2nd sphere is stationary, and so some of the equations are simplified to 0. I need the math to work when both bodies are in motion.
I've tried to convert the book's example to code, and puzzle out what should happen for the second sphere's line of action and normal- V2p and V2n. My code sort of works, but occasionally the velocities suddenly speed up and bounce out of control. Clearly there's something wrong with my math.
Here's what I'm using. The code is in Java, "s1" and "s2" are the spheres.
double e = 1d;
// distance of sphere centers
double dX = s2.getCenterX() - s1.getCenterX();
double dY = s2.getCenterY() - s1.getCenterY();
double tangent = dY / dX;
double angle = Math.atan(tangent);
// v1 line of action
double v1p = s1.getVelocityX() * Math.cos(angle) + s1.getVelocityY() * Math.sin(angle);
// v1 normal
double v1n = -s1.getVelocityX() * Math.sin(angle) + s1.getVelocityY() * Math.cos(angle);
// v2 line of action
double v2p = s2.getVelocityX() * Math.cos(angle) + s2.getVelocityY() * Math.sin(angle);
// v2 normal
double v2n = -s2.getVelocityX() * Math.sin(angle) + s2.getVelocityY() * Math.cos(angle);
double v1massScale = (s1.getMass() - (e * s2.getMass())) / (s1.getMass() + s2.getMass());
double v2massScale = ((1 + e) * s1.getMass()) / (s1.getMass() + s2.getMass());
// compute post-collision velocities
double v1pPrime = v1massScale * v1p + v2massScale * v2p;
double v2pPrime = v2massScale * v1p + v1massScale * v2p;
// rotate back to normal
double v1xPrime = v1pPrime * Math.cos(angle) - v1n * Math.sin(angle);
double v1yPrime = v1pPrime * Math.sin(angle) + v1n * Math.cos(angle);
double v2xPrime = v2pPrime * Math.cos(angle) - v2n * Math.sin(angle);
double v2yPrime = v2pPrime * Math.sin(angle) + v2n * Math.cos(angle);
| 0 | 0 | 0 | 0 | 1 | 0 |
Let there be two balls, one of which is moving about in the Cartesian coordinate plane, while the other is stationary and immobile. At some point, the moving ball collides with the inert ball. Assuming the moving ball is traveling in a straight line, how can one derive the new angle that the moving ball will be propelled given the following information:
The moving ball's center coordinates (X0, Y0), radius (R0), and angle of travel before impact (A0)
The stationary ball's center coordinates (X1, Y1) and radius (R1)
| 0 | 0 | 0 | 0 | 1 | 0 |
I'm trying to figure out if there is any existing AI tools/frameworks/Library for Objective C or Cocos [well OpenGL + Obj C] in general that's good for a person who's never done any form of AI before [other than the simple checkers or tic-tac-toe AI's]. The scenario here is I've finished the basics control of a game for the iPad and works fine for multi-player. The AI just needs to move around, similar to the classic game snakes and somehow 'trap' a human player. I now want to write an AI for this.
I found a thing called http://opensteer.sourceforge.net/ which appears to be pretty good, however it was last updated in 2004. Which was 7 years ago, and not sure if I should use it if there are other ones.
If anyone have any other suggestions of things I should look at, please guide me to the right area.
| 0 | 1 | 0 | 0 | 0 | 0 |
In basic words I need a simple and fast algorithm to find the solution X from C * X = M where all variable are matrices. More explanations below.
I'm trying to compute one specific matrix but it doesn't really work as expected:
Vz - negative Z-axis vector (or any other)
Vg - current gravity vector
Vc - zero reference vector (for gravity calibration)
M0 - current rotation matrix
C0 - reference rotation matrix
X0 - unknown rotation matrix to find
*t - transposed versions of above matrices
Upong runtime only Vg, M and C are known.
Rules:
1) Vz == Vg * M0
2) Vg == Vz * Mt
3) Vz == Vc * C0
4) Vc == Vz * Ct
5) Vz == Vx * X0
6) Vx == Vz * Xt
7) Vx == Vg * C0
8) M0 == C0 * X0 (wrong!!! see update notes below)
...
?) X0 = ?
I tried to use formula like that:
X0 = M0 * Ct
But the resulting matrix does not satifsy the rules (5) and (6) as expected.
Any ideas what's wrong here?
UPDATE:
The formula I tried (X0 = M0 * Ct) is correct.
The question was incorrect as (8) is actually M0 = X0 * C0.
The problem why I thought it doesn't work was because I tried to compute Vx = Vg * C0 - but actually neither Vx = Vg * C0 nor Vg = Vx * Ct are correct.
Thus I'm moving to the next task - that is better to describe as a new question :-)
| 0 | 0 | 0 | 0 | 1 | 0 |
I am not too much onto data mining but I require some ideas on clustering. Let me first describe my problem.
I have a around 100 data sheets which contain user reviews. I am trying to find for instances words that describe quality. One can say it is amazing quality another person can say great quality now I have to cluster those documents which describe those similar sentences and get the frequency of such sentences. What concept to apply here?
Guess I have to specify some stop words and synonyms. I am not too familiar with this concept.
Can some one give me some detailed links or explanation? and what tool to be used? I am basically a python programmer so any python module would be appreciated.
Thank You
| 0 | 1 | 0 | 0 | 0 | 0 |
Hi I was wondering if there is any known way to get rid of unnecessary parentheses in mathematical formula. The reason I am asking this question is that I have to minimize such formula length
if((-if(([V].[6432])=0;0;(([V].[6432])-([V].[6445]))*(((([V].[6443]))/1000*([V].[6448])
+(([V].[6443]))*([V].[6449])+([V].[6450]))*(1-([V].[6446])))))=0;([V].[6428])*
((((([V].[6443]))/1000*([V].[6445])*([V].[6448])+(([V].[6443]))*([V].[6445])*
([V].[6449])+([V].[6445])*([V].[6450])))*(1-([V].[6446])));
it is basically part of sql select statement. It cannot surpass 255 characters and I cannot modify the code that produces this formula (basically a black box ;) )
As you see many parentheses are useless. Not mentioning the fact that:
((a) * (b)) + (c) = a * b + c
So I want to keep the order of operations Parenthesis, Multiply/Divide, Add/Subtract.
Im working in VB, but solution in any language will be fine.
Edit
I found an opposite problem (add parentheses to a expression) Question.
I really thought that this could be accomplished without heavy parsing. But it seems that some parser that will go through the expression and save it in a expression tree is unevitable.
| 0 | 0 | 0 | 0 | 1 | 0 |
I'm trying to estimate the rate of convergence of a sequence.
background:
u^n+1 = G u_n, where G is a iteration matrix (coming from heat equation).
Fixing dx = 0.1, and setting dt = dx*dx/2.0 to satisfy the a stability constraint
I then do a number of iterations up to time T = 0.1, and calculate the error (analytical solution is known) using max-norm.
This gives me a sequence of global errors, which from the theory should be of the form O(dt) + O(dx^2).
Now, I want to confirm that we have O(dt).
How should I do this?
| 0 | 0 | 0 | 0 | 1 | 0 |
I'm looking at the CUDA SDK convolution with separable kernels, and I have a simple question but can't find an answer:
Do the vectors, whose convolution gives the kernel, need to have the same size? Can I first perform a row-convolution with a vector 1x3 and then a column convolution with another one 5x1 ? Or they both need to be same size? Google isn't helping (or I'm unable to search for an answer)
| 0 | 0 | 0 | 0 | 1 | 0 |
I'm doing a piece of university coursework, and I'm stuck with some Prolog.
The coursework is to make a really rudimentary Watson (the machine that answers questions on Jeapoardy).
Anyway, I've managed to make it output the following:
noun_phrase(det(the),np2(adj(traitorous),np2(noun(tostig_godwinson)))),
verb_phrase(verb(was),np(noun(slain)))).
But the coursework specifies that I now need to extract the first and second noun, and the verb, to make a more concise sentence; i.e. [Tostig_godwinson, was, slain].
I much prefer programming in languages like C etc., so I'm a bit stuck. If this were a procedural language, I'd use parsing tools, but Prolog doesn't have any... What do I need to do to extract those parts?
Thank you in advance
| 0 | 1 | 0 | 0 | 0 | 0 |
I have a very rudimentary camera which generates 3 vectors for use with gluLookAt(...) the problem is I'm not sure if this is correct, I adapted code from something my lecturer showed us (I think he got it from somewhere).
This actually works until you spin the mouse round in circles than camera starts to rotate around the z-axis. Which shouldn't happen as the mouse coords are only attached to the pitch and yaw not the roll.
Camera
// Camera.hpp
#ifndef MOOT_CAMERA_INCLUDE_HPP
#define MOOT_CAMERA_INCLUDE_HPP
#include <GL/gl.h>
#include <GL/glu.h>
#include <boost/utility.hpp>
#include <Moot/Platform.hpp>
#include <Moot/Vector3D.hpp>
namespace Moot
{
class Camera : public boost::noncopyable
{
protected:
Vec3f m_position, m_up, m_right, m_forward, m_viewPoint;
uint16_t m_height, m_width;
public:
Camera()
{
m_forward = Vec3f(0.0f, 0.0f, -1.0f);
m_right = Vec3f(1.0f, 0.0f, 0.0f);
m_up = Vec3f(0.0f, 1.0f, 0.0f);
}
void setup(uint16_t setHeight, uint16_t setWidth)
{
m_height = setHeight;
m_width = setWidth;
}
void move(float distance)
{
m_position += (m_forward * distance);
}
void addPitch(float setPitch)
{
m_forward = (m_forward * cos(setPitch) + (m_up * sin(setPitch)));
m_forward.setNormal();
// Cross Product
m_up = (m_forward / m_right) * -1;
}
void addYaw(float setYaw)
{
m_forward = ((m_forward * cos(setYaw)) - (m_right * sin(setYaw)));
m_forward.setNormal();
// Cross Product
m_right = m_forward / m_up;
}
void addRoll(float setRoll)
{
m_right = (m_right * cos(setRoll) + (m_up * sin(setRoll)));
m_right.setNormal();
// Cross Product
m_up = (m_forward / m_right) * -1;
}
virtual void apply() = 0;
}; // Camera
} // Moot
#endif
Snippet from update cycle
// Mouse movement
m_camera.addPitch((float)input().mouseDeltaY() * 0.001);
m_camera.addYaw((float)input().mouseDeltaX() * 0.001);
apply() in the camera class is defined in an inherited class, which is called from the draw function of the game loop.
void apply()
{
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective(40.0,(GLdouble)m_width/(GLdouble)m_height,0.5,20.0);
m_viewPoint = m_position + m_forward;
gluLookAt( m_position.getX(), m_position.getY(), m_position.getZ(),
m_viewPoint.getX(), m_viewPoint.getY(), m_viewPoint.getZ(),
m_up.getX(), m_up.getY(), m_up.getZ());
}
| 0 | 0 | 0 | 0 | 1 | 0 |
I'm writing a 3D Minesweeper-type game, so given an a[x][y][z], I need to calculate the sum of the surrounding values assuming they aren't out of bounds.
My question is how can I do this without having a zillion checks for:
if ((x>0)&&(x<ARRAY_SIZE))
for x, y, and z?
Thanks
| 0 | 0 | 0 | 0 | 1 | 0 |
I've to compare 4 variables a,b,c,d if any of them is -1 return false.
and How mush terse this could be ?
may be some mathematical operation could be done !! I dont like wasting so many characters or lines for this simple thing.
| 0 | 0 | 0 | 0 | 1 | 0 |
I have the following Haskell code
import Data.Int
import System.Environment
type Coord = (Int16, Int16)
distributePointsOverCircle :: Int16 -> Int16 -> [Coord]
distributePointsOverCircle points radius =
[ (xOf point, yOf point) | point <- [1..points] ]
where
xOf x = abstract cos x
yOf x = abstract sin x
abstract :: RealFrac a => ( a -> a ) -> Int16 -> Int16
abstract f x = (radius *) . truncate . f . fromIntegral $ (angleIncrement * x) * truncate (pi / 180)
angleIncrement = div 360 points
main = do
[a,b] <- getArgs
print $ distributePointsOverCircle (read a) (read b)
No matter what I pass to distributePointsOverCircle, it consistently gives me a list of however many Coords as I give points where each Coord's first element is the radius and second element is zero. Obviously this is not an even distribution of points.
What am I doing wrong here? Is there some type-system trickery fudging my numbers? The function I am trying to produce, written in an imperative pseudocode would be.
distributePointsOverCircle( numberOfPoints, radius )
angleIncrement = 360 / numberOfPoints
points = []
for i in 0 to (numberOfPoints -1)
p = Point()
p.x = (radius * cos((angleIncrement * i) * (PI / 180)))
p.y = (radius * sin((angleIncrement * i) * (PI / 180)))
points[i] = p
return points
| 0 | 0 | 0 | 0 | 1 | 0 |
Using Python, assume I'm running through a known quantity of items I, and have the ability to time how long it takes to process each one t, as well as a running total of time spent processing T and the number of items processed so far c. I'm currently calculating the average on the fly A = T / c but this can be skewed by say a single item taking an extraordinarily long time to process (a few seconds compared to a few milliseconds).
I would like to show a running Standard Deviation. How can I do this without keeping a record of each t?
| 0 | 0 | 0 | 0 | 1 | 0 |
I am currently writing a calculator application. I am trying to write a derivative estimator into it. The formula below is a simple way to do it. Normally on paper you would use the smallest h possible to get the most accurate estimate. The problem is doubles can't handle adding really small numbers to comparatively huge numbers. Such as 4+1E-200 will just result in 4.0. Even if h was just 1E-16, 4+1E16 will in fact give you the right value but doing math it it is inaccurate because anything after the 16th place is lost and rounding can't happen correctly. I have heard the general rule of thumb for doubles is 1E-8 or 1E-7. The issue with this is large numbers wont work as 2E231+1E-8 will just be 2E23, the 1E-8 will be lost because of size issues.
f'(x)=(f(x+h)-f(x))/h as x approaches 0
When I test f(x)=x^2 at the point 4 so f'(4), it should be exactly 8
now I understand that I will probably never get exactly 8. but I the most accurate seems to be around 1E-7 or 1E8
the funny thing is 1E-9 all the to 1E-11 give the same answer.
Here is a list of h's and results for f(x)=x^2 at x=4
1E-7 8.000000129015916
1E-8 7.999999951380232
1E-9 8.000000661922968
1E-10 8.000000661922968
1E-11 8.000000661922968
1E-12 8.000711204658728
Here are my questions:
What is the best way to pick h, obviously 1E-8 or 1E-7 make sense but how can I pick an h based off of x, so that it will work with any sized number even if x is 3.14E203 or 2E-231.
How many decimals of precision should I account for.
Do you have any idea how Texas instruments does it, the TI 83, 84, and Inspire can numerically figure out derivatives to 12 decimals or precision and almost always be right, but the maximum precision of their numbers is 12 digits anyway and those calculators are non CAS so they aren’t actually deriving anything
Logically there is a number somewhere between 1E-7 and 1E-8 that will give me a more precise result, is there any way to find that number, or at least get close to it.
ANSWERED
Thank you very much BobG. The application is currently planned to be in 2 forms, a command line PC application . And an Android application. You will be mentioned in the special thanks to portions of the About page. If you would like it will be open source but I am not posting links to the project site until I work out some very very large bugs. At the moment I have been calling it Mathulator, but the name will likely change because there is already a copyright on it and it sounds stupid.I have no clue when the release candidate will be running, at the moment I have no clue when it will be stable. But it will be very powerful if I can implement everything I want too.Thanks again. Happy Programming.
| 0 | 0 | 0 | 0 | 1 | 0 |
im doing the 8 puzzle solver with the a star algorithm. I implement Manhattan and misplaced heuristic functions in this solver. In some cases, the solver works fine. But in some cases, it takes a lot of time to find the solution. I think that one of my problem is in the function that looks for the node with the lowest value in the open list(waiting for expansion).
a part of psedocode(from wiki)
while openset is not empty
x := the node in openset having the lowest f_score[] value
if x = goal
return reconstruct_path(came_from, came_from[goal])
................................
So what is the best way to find the lowest f_score value? Just find the minimum value, or we have to modify the list when we have a state to add( sort the list when we add the state) so the minimum value will be in the first position.
| 0 | 1 | 0 | 0 | 0 | 0 |
I am writing a project that works with NLP (natural language parser). I am using the stanford parser.
I create a thread pool that takes sentences and run the parser with them.
When I create one thread its all works fine, but when I create more, I get errors.
The "test" procedure is finding words that have some connections.
If I do an synchronized its supposed to work like one thread but still I get errors.
My problem is that I have errors on this code:
public synchronized String test(String s,LexicalizedParser lp )
{
if (s.isEmpty()) return "";
if (s.length()>80) return "";
System.out.println(s);
String[] sent = s.split(" ");
Tree parse = (Tree) lp.apply(Arrays.asList(sent));
TreebankLanguagePack tlp = new PennTreebankLanguagePack();
GrammaticalStructureFactory gsf = tlp.grammaticalStructureFactory();
GrammaticalStructure gs = gsf.newGrammaticalStructure(parse);
Collection tdl = gs.typedDependenciesCollapsed();
List list = new ArrayList(tdl);
//for (int i=0;i<list.size();i++)
//System.out.println(list.get(1).toString());
//remove scops and numbers like sbj(screen-4,good-6)->screen good
Pattern p = Pattern.compile(".*\\((.*?)\\-\\d+,(.*?)\\-\\d+\\).*");
if (list.size()>2){
// Split input with the pattern
Matcher m = p.matcher(list.get(1).toString());
//check if the result have more than 1 groups
if (m.find()&& m.groupCount()>1){
if (m.groupCount()>1)
{
System.out.println(list);
return m.group(1)+m.group(2);
}}
}
return "";
}
the errors that I have are:
at blogsOpinions.ParserText.(ParserText.java:47)
at blogsOpinions.ThreadPoolTest$1.run(ThreadPoolTest.java:50)
at blogsOpinions.ThreadPool$PooledThread.run(ThreadPoolTest.java:196)
Recovering using fall through
strategy: will construct an (X ...)
tree. Exception in thread
"PooledThread-21"
java.lang.ClassCastException:
java.lang.String cannot be cast to
edu.stanford.nlp.ling.HasWord
at
edu.stanford.nlp.parser.lexparser.LexicalizedParser.apply(LexicalizedParser.java:289)
at blogsOpinions.ParserText.test(ParserText.java:174)
at blogsOpinions.ParserText.insertDb(ParserText.java:76)
at blogsOpinions.ParserText.(ParserText.java:47)
at blogsOpinions.ThreadPoolTest$1.run(ThreadPoolTest.java:50)
at blogsOpinions.ThreadPool$PooledThread.run(ThreadPoolTest.java:196)
and how can i get the discription of the subject like the screen is very good, and I want to get screen good from the list the I get and not like list.get(1).
| 0 | 1 | 0 | 0 | 0 | 0 |
I have midpoint of triangle and also i don't other vertex information So how will i calculate height of triangle with mid-point formula?
sorry i m editing it.although this is math problem but i am making computer program.I had vertex information this is being lost in program execution so i m keeping only midpoint.So in flow of program i have only midpoint information.So how will i calculate height of triangle if i have triangle vertex like (-0.5,0), (0.5,0),(0.0,1).
| 0 | 0 | 0 | 0 | 1 | 0 |
I have a polynomial of the fifth order:
y = ax5 + bx4 + cx3 + dx2 + ex + f
The coefficients a-f are known and I need to calculate x for a given y. I could probably use the Newton-Raphson algorithm or similar, but would prefer a non-iterative solution if possible.
Edit: I guess I didn't think this through enough before posting my question. My polynomial coefficients have been calculated from sampled data and in this special case there is only one root. It didn't pass my mind that there, of course, might be five different roots in the general case. I think I will fit the sampled data to an inverse polynomial as well, and use that to calculate x from y.
| 0 | 0 | 0 | 0 | 1 | 0 |
I need to analyze the text to exist in it banned words. Suppose the black list is the word: "Forbid". The word has many forms. In the text the word can be, for example: "forbidding", "forbidden", "forbad". To bring the word to the initial form, I use a process lemmatization. Your suggestions?
What about typos?
For example: "F0rb1d". I think use damerau–Levenshtein or another. You suggestions?
And what if the text is written as follows:
"ForbiddenInformation.Privatecorrespondenceofthecompany." OR
"F0rb1dden1nformation.Privatecorresp0ndenceofthec0mpany." (yes, without whitespace)
How to solve this problem?
Preferably fast algorithm, because text are processed in real time.
And maybe what some tips to improve performance (how to store, etc)?
| 0 | 1 | 0 | 0 | 0 | 0 |
$html=strip_tags($html);
$html=ereg_replace("[^A-Za-zäÄÜüÖö]"," ",$html);
$words = preg_split("/[\s,]+/", $html);
doesnt this replace all non (A-Z, a-z, a o u with umlauts) characters with space?
I am losing words like zugänglich etc with umlauts
is there any thing wrong with the regex?
edit:
I replaced ereg_replace with preg_replace but somehow the special characters like :, ® are not getting replace by space...
| 0 | 1 | 0 | 0 | 0 | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.