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 a standalone Java application below that is:
Generating a random line
Applied to a 2D grid where each cell value is the distance along the line perpindicular to the line
Finds the rise/run and attempts to calculate the original linear equation from the grid
Applies new line to another grid and prints out the greatest difference compared to the first grid
I expected the two grids to have identical values. The gradient lines may be different since the lines can extend outside the area of the grid, but should be similar and in two cases identical.
So is the problem a poor understanding of math, a bug in my code or a misunderstanding of floating point values?
import java.awt.geom.Point2D;
import java.awt.geom.Line2D;
import java.util.Iterator;
import java.util.ArrayList;
public final class TestGradientLine {
private static int SIZE = 3;
public TestGradientLine() {
super();
}
//y = mx + b
//b = y - mx
//m is rise / run = gradient
//width and height of bounding box
//for a box 10x10 then width and height are 9,9
public static Line2D getGradientLine(double run, double rise, double width, double height, double x, double y) {
if (run == 0 && rise == 0) {
return new Line2D.Double(x, y, x + width, y + height);
}
//calculate hypotenuse
//check for a vertical line
if (run == 0) {
return new Line2D.Double(x, y, x, y + height);
}
//check for a horizontal line
if (rise == 0) {
return new Line2D.Double(x, y, x + width, y);
}
//calculate gradient
double m = rise / run;
Point2D start;
Point2D opposite;
if (m < 0) {
//lower left
start = new Point2D.Double(x, y + height);
opposite = new Point2D.Double(x + width, y);
} else {
//upper left
start = new Point2D.Double(x, y);
opposite = new Point2D.Double(x + width, y + height);
}
double b = start.getY() - (m * start.getX());
//now calculate another point along the slope
Point2D next = null;
if (m > 0) {
next = new Point2D.Double(start.getX() + Math.abs(run), start.getY() + Math.abs(rise));
} else {
if (rise < 0) {
next = new Point2D.Double(start.getX() + run, start.getY() + rise);
} else {
next = new Point2D.Double(start.getX() - run, start.getY() - rise);
}
}
final double actualWidth = width;
final double actualHeight = height;
final double a = Math.sqrt((actualWidth * actualWidth) + (actualHeight * actualHeight));
extendLine(start, next, a);
Line2D gradientLine = new Line2D.Double(start, next);
return gradientLine;
}
public static void extendLine(Point2D p0, Point2D p1, double toLength) {
final double oldLength = p0.distance(p1);
final double lengthFraction =
oldLength != 0.0 ? toLength / oldLength : 0.0;
p1.setLocation(p0.getX() + (p1.getX() - p0.getX()) * lengthFraction,
p0.getY() + (p1.getY() - p0.getY()) * lengthFraction);
}
public static Line2D generateRandomGradientLine(int width, int height) {
//so true means lower and false means upper
final boolean isLower = Math.random() > .5;
final Point2D start = new Point2D.Float(0, 0);
if (isLower) {
//change origin for lower left corner
start.setLocation(start.getX(), height - 1);
}
//radius of our circle
double radius = Math.sqrt(width * width + height * height);
//now we want a random theta
//x = r * cos(theta)
//y = r * sin(theta)
double theta = 0.0;
if (isLower) {
theta = Math.random() * (Math.PI / 2);
} else {
theta = Math.random() * (Math.PI / 2) + (Math.PI / 2);
}
int endX = (int)Math.round(radius * Math.sin(theta));
int endY = (int)Math.round(radius * Math.cos(theta)) * -1;
if (isLower) {
endY = endY + (height - 1);
}
final Point2D end = new Point2D.Float(endX, endY);
extendLine(start, end, radius);
return new Line2D.Float(start, end);
}
public static Point2D getNearestPointOnLine(Point2D end, Line2D line) {
final Point2D point = line.getP1();
final Point2D start = line.getP2();
double a = (end.getX() - point.getX()) * (start.getX() - point.getX()) + (end.getY() - point.getY()) * (start.getY() - point.getY());
double b = (end.getX() - start.getX()) * (point.getX() - start.getX()) + (end.getY() - start.getY()) * (point.getY() - start.getY());
final double x = point.getX() + ((start.getX() - point.getX()) * a)/(a + b);
final double y = point.getY() + ((start.getY() - point.getY()) * a)/(a + b);
final Point2D result = new Point2D.Double(x, y);
return result;
}
public static double length(double x0, double y0, double x1, double y1) {
final double dx = x1 - x0;
final double dy = y1 - y0;
return Math.sqrt(dx * dx + dy * dy);
}
public static void main(String[] args) {
final Line2D line = generateRandomGradientLine(SIZE, SIZE);
System.out.println("we're starting with line " + line.getP1() + " " + line.getP2());
double[][] region = new double[SIZE][SIZE];
//load up the region with data from our generated line
for (int x = 0; x < SIZE; x++) {
for (int y = 0; y < SIZE; y++) {
final Point2D point = new Point2D.Double(x, y);
final Point2D nearestPoint = getNearestPointOnLine(point, line);
if (nearestPoint == null) {
System.err.println("uh -oh!");
return;
}
final double distance = length(line.getP1().getX(),
line.getP1().getY(), nearestPoint.getX() + 1,
nearestPoint.getY() + 1);
region[x][y] = distance;
}
}
//now figure out what our line is from the region
double runTotal = 0;
double riseTotal = 0;
double runCount = 0;
double riseCount = 0;
for (int x = 0; x < SIZE; x++) {
for (int y = 0; y < SIZE; y++) {
if (x < SIZE - 1) {
runTotal += region[x + 1][y] - region[x][y];
runCount++;
}
if (y < SIZE - 1) {
riseTotal += region[x][y + 1] - region[x][y];
riseCount++;
}
}
}
double run = 0;
if (runCount > 0) {
run = runTotal / runCount;
}
double rise = 0;
if (riseCount > 0) {
rise = riseTotal / riseCount;
}
System.out.println("rise is " + rise + " run is " + run);
Line2D newLine = getGradientLine(run, rise, SIZE - 1, SIZE - 1, 0, 0);
System.out.println("ending with line " + newLine.getP1() + " " + newLine.getP2());
double worst = 0.0;
int worstX = 0;
int worstY = 0;
for (int x = 0; x < SIZE; x++) {
for (int y = 0; y < SIZE; y++) {
final Point2D point = new Point2D.Double(x, y);
final Point2D nearestPoint = getNearestPointOnLine(point, newLine);
if (nearestPoint == null) {
System.err.println("uh -oh!");
return;
}
final double distance = length(line.getP1().getX(),
line.getP1().getY(), nearestPoint.getX() + 1,
nearestPoint.getY() + 1);
final double diff = Math.abs(region[x][y] - distance);
if (diff > worst) {
worst = diff;
worstX = x;
worstY = y;
}
}
}
System.out.println("worst is " + worst + " x: " + worstX + " y: " + worstY);
}
}
| 0
| 0
| 0
| 0
| 1
| 0
|
I'm currently in the throes of writing a system based on subdividing space (it's for a game), I need to be able to test if a circle completely contains a square.
For bonus points, I should point out that my system works in N dimensions, so if your algorithm works by looping through each dimension and doing something, present it as such ;)
| 0
| 0
| 0
| 0
| 1
| 0
|
Problem: How many of the first 100,000,000 hexagonal numbers are divisible by all the numbers from 1 through 20?
2nd solution - simple brute force (does work)
public static void main(String[] args) {
long hnr = 100000000L, count = 0L;
for (long i = 1, h = getHexNr(i); i <= hnr; i++, h = getHexNr(i))
if (h % 2 == 0 && h % 3 == 0 && h % 4 == 0 && h % 5 == 0
&& h % 6 == 0 && h % 7 == 0 && h % 8 == 0
&& h % 9 == 0 && h % 10 == 0 && h % 11 == 0
&& h % 12 == 0 && h % 13 == 0 && h % 14 == 0
&& h % 15 == 0 && h % 16 == 0 && h % 17 == 0
&& h % 18 == 0 && h % 19 == 0 && h % 20 == 0) count++;
System.out.println(count);
}
1st solution (does not work)
public static void main(String[] args) {
long nr = 1L, hnr = 100000000L, count = 0L;
double tmp = 0;
for (long i = 2L; i < 21; i++)
nr = lcm(nr, i);
for (double qes : getQES(2, 1, -nr)) {
if (qes < 0) continue;
int limit = (int) (getHexNr(hnr) / Math.floor(qes));
for (int i = 0; i < limit; i++) {
// if ((i * qes) % 1 == 0) count++;
if ((tmp += qes) % 1 == 0) count++;
}
}
System.out.println(count);
}
And utils:
static long gcd(long a, long b) {
if (b == 0) return Math.abs(a);
return gcd(b, a % b);
}
static long lcm(long a, long b) {
return (a * b) / gcd(a, b);
}
static long getHexNr(long n) {
return n * (2 * n - 1);
}
static double[] getQES(long a, long b, long c) {
double d = b * b - 4 * a * c;
if (d < 0) return new double[0];
return new double[] { (-b + Math.sqrt(d)) / (2 * a),
(-b - Math.sqrt(d)) / (2 * a) };
}
What is going wrong with first solution? (decimal precision?)
edit:
Algorithm for solution 1:
find smalles number x evenly divisible by all of the numbers from 1 to 20
solve quadratic equation derived from hex number formula x = n * (2 * n - 1)
if multible of n is without residue increase count
repeat 3. while multiple of n is smaller then 100000000'th hexagonal number
edit 2:
232792560 // right
[10788.460769248566, -10788.960769248566] // right
numbers like 6418890 are passing the test, google "6418890*10788.460769248566%1="
edit 3:
Yes, brute force version should check evenly divisibility of only primes below 21. But rather more interesting was to find out, what Goldberg talked about. I did know about it, but more of like five monkeys story.
Bit later, i thought about rounding the number, when i remembered, that Math library does not contain function to do this. But i could use BigDecimal, and when i looked up BigDecimal and double i found this. What a pleasant deja vu.
And rounding looks like:
public static double round(double d, int nr) {
return new BigDecimal(Double.toString(d)).setScale(nr,
BigDecimal.ROUND_HALF_UP).doubleValue();
}
| 0
| 0
| 0
| 0
| 1
| 0
|
I am working in a natural language processing project. It aims to build libraries for Arabic language. We working on a POS tagger and now I am thinking in grammar phase. Since Arabic language and many others have complicated grammar, so it is very hard to build their context free grammar (CFG). For this reason I had an idea for an algorithm to build a CFG (with probability PCFG) for any language from a tagger corpora using unsupervised learning. To explain the algorithm suppose I have these three tagged statements as an input:
1- Verb Noun
2- Verb Noun Subject
3- Verb Noun Subject adverb
The algorithm gives:
1) A--> Verb Noun
2) B-->A Subject
3) C-->B adverb.
We repeat this methodology for each statement such that we can finish with a specific PCFG. The main power of the algorithm lies beyond the fact of seeing the whole statement, so the probabilities can be conditional and they are specific. After that CKY algorithm can be applied to choose the best tree for new statements using probabilities.
Do you expect that this algorithm is good or not and does it worth to continue improving it.
| 0
| 1
| 0
| 0
| 0
| 0
|
I have five values, A, B, C, D and E.
Given the constraint A + B + C + D + E = 1, and five functions F(A), F(B), F(C), F(D), F(E), I need to solve for A through E such that F(A) = F(B) = F(C) = F(D) = F(E).
What's the best algorithm/approach to use for this? I don't care if I have to write it myself, I would just like to know where to look.
EDIT: These are nonlinear functions. Beyond that, they can't be characterized. Some of them may eventually be interpolated from a table of data.
| 0
| 0
| 0
| 0
| 1
| 0
|
I have this complex iterations program I wrote in TI Basic to perform a basic iteration on a complex number and then give the magnitude of the result:
INPUT “SEED?”, C
INPUT “ITERATIONS?”, N
C→Z
For (I,1,N)
Z^2 + C → Z
DISP Z
DISP “MAGNITUDE”, sqrt ((real(Z)^2 + imag(Z)^2))
PAUSE
END
What I would like to do is make a Haskell version of this to wow my teacher in an assignment. I am still only learning and got this far:
fractal ::(RealFloat a) =>
(Complex a) -> (Integer a) -> [Complex a]
fractal c n | n == a = z : fractal (z^2 + c)
| otherwise = error "Finished"
What I don't know how to do is how to make it only iterate n times, so I wanted to have it count up a and then compare it to n to see if it had finished.
How would I go about this?
| 0
| 0
| 0
| 0
| 1
| 0
|
Suppose we have two longs, x and y. What operator or function involving x and y would produce another long, z, which is least likely to be equal to the result of applying the same operator or function to different of x's and y's?
Ex: Addition would be a poor choice. 1+4=5, but 2+3 also equals 5.
EDIT: Let me explain why I'm asking this question. I'm creating a space rpg game. The game's environment (solarsystems) will be procedurally generated from two seeds. These seeds consist of the x and y coordinates of the system in the universe. So there is a good probability that the player might encounter the systems at (500,501) and (501,500) over the course of his adventures. I need a way to these the solar systems generated unique. But also, I want to make sure that as many coordinate pairs as possible will produce unique seeds.
EDIT 2: I tested two of the solutions given to me. Accipitridae's answer was far superior to Artelius's answer. Here's the code to test the solutions:
HashSet<Long> set = new HashSet<Long>();
for(int x=0; x<1000; x++)
for(int y=0; y<1000; y++)
//I commented out one of the solutions at a time
set.add((long)(((x&0x7FFFFFFF) << 33) | ((y&0x7FFFFFFF) << 2) | ((x>>>62) & 2) | (y>>>63)));//Artelius
set.add((long)(x - y * 7046029254386353131l));//Accipitridae
System.out.println(set.size());
From the size of the HashSet, I could tell how many unique seeds were generated through each method. For these parameters, Artelius's solution generated 2048 unique longs, while Accipitridae's generated 1000000, meaning that there were no collisions at all.
Thank you all for you effort in trying to solve this problem. :)
| 0
| 0
| 0
| 0
| 1
| 0
|
If I have a camera which gives out 360 degree pan (x) and tilt (y) values, and I want to get the pan and tilt values of where I have my cursor in the camera's view, how would I convert that?
More info:
It's a Flash/AS3 project.
The pan and tilt values are from the center of the camera view.
Camera view size is 960x540.
| 0
| 0
| 0
| 0
| 1
| 0
|
I'm using some fairly straight-forward SQL code to calculate the coefficients of regression (intercept and slope) of some (x,y) data points, using least-squares. This gives me a nice best-fit line through the data. However we would like to be able to see the 95% and 5% confidence intervals for the line of best-fit (the curves below).
(source: curvefit.com)
What these mean is that the true line has 95% probability of being below the upper curve and 95% probability of being above the lower curve. How can I calculate these curves? I have already read wikipedia etc. and done some googling but I haven't found understandable mathematical equations to be able to calculate this.
Edit: here is the essence of what I have right now.
--sample data
create table #lr (x real not null, y real not null)
insert into #lr values (0,1)
insert into #lr values (4,9)
insert into #lr values (2,5)
insert into #lr values (3,7)
declare @slope real
declare @intercept real
--calculate slope and intercept
select
@slope = ((count(*) * sum(x*y)) - (sum(x)*sum(y)))/
((count(*) * sum(Power(x,2)))-Power(Sum(x),2)),
@intercept = avg(y) - ((count(*) * sum(x*y)) - (sum(x)*sum(y)))/
((count(*) * sum(Power(x,2)))-Power(Sum(x),2)) * avg(x)
from #lr
Thank you in advance.
| 0
| 0
| 0
| 0
| 1
| 0
|
In our discrete mathematics course in my university, the teacher shows his students the Ackermann function and assign the student to develop the function on paper.
Beside being a benchmark for recursion optimisation, does the Ackermann function has any real uses ?
| 0
| 0
| 0
| 0
| 1
| 0
|
If M is prime, how to choose a and b to minimize collisions?
Also in books it is written that to find the empty slot while quadratic probing in (f(k)+j^2) % M, the hash table has to be at least half empty? Can someone provide me a proof of that?
| 0
| 0
| 0
| 0
| 1
| 0
|
I have a bunch of vectors normal to window surfaces in a 3D modelling software. Projected to the XY-Plane, I would like to know in which direction they are facing, translated to the 8 compass coordinates (North, North-East, East, South-East, South, South-West, West and North-West).
The vectors work like this:
the X axis represents East-West (with East being positive)
the y axis represents North-South (with North being positive)
thus
(0, 1) == North
(1, 0) == East
(0,-1) == South
(-1,0) == West
Given a vector (x, y) I am looking for the closest of the 8 compass coordinates. Any ideas on how to do this elegantly?
| 0
| 0
| 0
| 0
| 1
| 0
|
Is there a simple way to do this
if (1 < x && x < 3) { .... }
I want something like this:
if (1 < x < 3) { .... }
I know that the code above is wrong but....
Thanks
| 0
| 0
| 0
| 0
| 1
| 0
|
I wrote a drawing function that draws various on-screen sprites. These sprites can only overlap up to a point. If they have to much overlap, they become too obscured. As a result I need to detect when these sprites are too much overlapped. Luckily, the problem is simplified in that the sprites can be treated as orthogonal rectangles. I'd like to know by how much these rectangles overlap. Right now, I just brute force it by testing each pixel in one rectangle to see if the other contains it. I count these and calculate the percentage overlap. I think there's probably a better, less brute force approach. What algorithm can I use to determine this?
I'm using wxwidgets.
| 0
| 0
| 0
| 0
| 1
| 0
|
my primary language is spanish, but I use all my software in english, including windows; however I'd like to use speech recognition in spanish.
Do you know if there's a way to use vista's speech recognition in other language than the primary os language?
| 0
| 1
| 0
| 0
| 0
| 0
|
Is there a way to find potential numeric overflows in Java code, using the Eclipse IDE? For example...
long aLong = X * Y * Z;
... where X, Y, and Z are ints and the result may overflow Integer.MAX_VALUE. (Note that, perhaps counter-intuitively, if the result in this example overflows Integer.MAX_VALUE, aLong will be assigned the erroneous overflowed value).
I've looked in Eclipse's Warnings settings, PMD rules, and FindBugs rules and I can't find any setting to help with this. A co-worker notes that IntelliJ will warn about this... and I'd hate to have to admit that I can't do the same with Eclipse. ;-)
Clarification 1: I'm not looking for something that gives 0 false positives... just warnings that "you may have an overflow problem here".,
Clarification 2: This is desired at "development time"... meaning, at the same stage that Eclipse is looking for unused imports, PMD is checking its rules, etc.
| 0
| 0
| 0
| 0
| 1
| 0
|
I am currently writing a bot for a MMORPG. Though, currently I am stuck at trying to figure out how to nicely implement this. The design problem is related to casting the character spells in the correct order. Here is a simple example to what I need to archieve. It's not related to casting them, but doing it in the correct order. I would know how simply cast them randomly, by checking which skill has not yet been casted, but in right order as being shown in the GUI, not really.
note: the skill amount may differ, it's not always 3, maximum 10 though.
Charactername < foobar > has 3 skills.
Skill 1: Name ( random1 ) cooldown ( 1000 ms ) cast duration ( 500 ms )
Skill 2: Name ( random2 ) cooldown ( 1500 ms ) cast duration ( 700 ms )
Skill 3: Name ( random3 ) cooldown ( 2000 ms ) cast duration ( 900 ms )
I don't really know how I could implement this, if anyone has some thoughts, feel free to share. I do know that most of the people don't like the idea of cheating in games, I don't like it either, nor I am actually playing the game, but its an interesting field for me.
Thank you.
| 0
| 1
| 0
| 0
| 0
| 0
|
Those who have worked or working in artificial intelligence(or equivalent) area should be knowing the AO* algorithm very well.
Its pretty clear that it is a generalized algorithm.
Do anybody of you have come across any practical application of the AO* algorithm?Some of you might already have worked on it.
So it would be great if you can share your thoughts or experience on AO* algorithm, how it can actually be used practically. what is the power of it?
Those who don't know the AO* algorithm, can refer following pdf (size -291 KB)
Generalized AO* algorithm
| 0
| 1
| 0
| 0
| 0
| 0
|
Currently, generics in C# do not allow any sane way to perform arithmetic. There are awkward workarounds available, but none of them are very neat and all of them reduce performance.
According to this interview, an interface with arithmetic types is not possible to implement, and so one such workaround is suggested.
But what you could do is have your Matrix take as an argument a Calculator, and in Calculator, have a method called multiply. You go implement that and you pass it to the Matrix.
Why should I have to tell an advanced programming language how to add and multiply numbers?
[Edited due to popular demand]
Why not simply allow a Generic to be restricted to a list of types?
Eg.
class Matrix<T> where T : int,long,float,double
The syntax could of course be different. But the compiler needs only to check that the type is on the list, and that the operators used work on all types, which should be much simpler than the apparently-too-difficult interface suggestion.
Are there any obvious reasons as to why this cannot be implemented?
| 0
| 0
| 0
| 0
| 1
| 0
|
I'm trying to better understand what exactly this code is doing. It's written in Objective-C, but should be familiar to anyone with a C background. What exactly are sin/cos mathematics doing here? Also, does anyone have a good recommendation for learning trig for gaming concepts such as these?
for (int i = 0; i < GAME_CIRCLES; i++)
{
point.x = center.x - sin (degree) * RADIUS;
point.y = center.y + cos (degree) * RADIUS;
mPieRect[i] = CGRectMakeWithCenter (point, RADIUS - 4);
degree += PI / 3.0;
}
| 0
| 0
| 0
| 0
| 1
| 0
|
Why this code 7.30 - 7.20 in ruby returns 0.0999999999999996, not 0.10?
But if i'll write 7.30 - 7.16, for example, everything will be ok, i'll get 0.14.
What the problem, and how can i solve it?
| 0
| 0
| 0
| 0
| 1
| 0
|
I'm trying to make a flashing object, i.e., increment it's alpha value from 0 to 255 (gradually) and then back down to 0, and repeat.
Is there a way I can do this without using some boolean? Getting it to increment is easy:
alpha = time.elapsed()%256;
But what's a nice way to get it to count back down again after that?
| 0
| 0
| 0
| 0
| 1
| 0
|
I'm trying to figure out a way to algorithmically get the amplitude and phase of a function that has sinusoidal terms in the Maxima computer algebra system. This only applies to steady state (as t -> infinity and the transients decay). For example, a trivial case would be:
f(t) = 1 / w * sin(w * t + theta) + exp(-a * t) + 8
In this case, the gain would be 1 / w, the phase offset would be theta, and we would ignore the transient term exp(-a * t) because we only care about the steady state gain and phase delay, and exp(-a * t) -> 0 as t -> infinity. We would also ignore the "+ 8" term because it's just a DC offset. The way I've been taught to do it in my engineering classes requires a lot of heuristics and tedious rearranging of equations to get them in a form similar to the above, where the answer is obvious just from looking at it.
Does anyone know of a general, algorithmic method of finding the gain and phase delay assuming they exist, given that I have the full power of a computer algebra system (and the standard functions that one would expect a CAS to have) to throw at it? Although I will likely be implementing it in Maxima, I would certainly appreciate generic answers explained just in terms of math.
Edit: I thought it was abundantly clear from my example that I want the answer symbolically, in terms of w. w is really supposed to be omega, and represents the frequency of the input. What I'm really asking is whether there are any standard math operations that will produce the gain and phase terms without a bunch of heuristic, manual equation rearranging.
| 0
| 0
| 0
| 0
| 1
| 0
|
If I have a set of values (which I'll call x), and a number of subsets of x:
What is the best way to work out all possible combinations of subsets whose union is equal to x, but none of whom intersect with each other.
An example might be:
if x is the set of the numbers 1 to 100, and I have four subsets:
a = 0-49
b = 50-100
c = 50-75
d = 76-100
then the possible combinations would be:
a + b
a + c + d
| 0
| 0
| 0
| 0
| 1
| 0
|
I am working on a project (C# and .NET Framework) which requires me to solve some partial differential equations. Are there any specific libraries based on .NET Framework that I could see and make my work simpler?
I have worked with MATLAb and solving partial differential equations is very straightforward there. How can I solve this problem?
| 0
| 0
| 0
| 0
| 1
| 0
|
My DotNET application has a limited scripting language build in (modelled loosely on VBScript) mainly for post-processing numbers, points and vectors. I've just added support for complex numbers, but I'm struggling with the notation.
I don't want to use the A + Bi notation, since it is not a clear division if A or B are defined as equations already:
31 * 5 + 6 + -5i
This could be interpreted as:
A = 31 * 5 + 6
B = -5i
and:
A = 31 * 5
B = 6 + -5i
None of the programming languages I know have native support for complex numbers. I'm thinking something like the following might work, but I'd appreciate any input on this:
{31 * 5} + {6 + -5}i
complex(31 * 5, 6 + -5)
r{31 * 5} i{6 + -5}
| 0
| 0
| 0
| 0
| 1
| 0
|
My degree is in Electrical and Computer Engineering but i'm currently employed as a Software Engineer. I took all of the algebra, geometry and calculus classes that one would expect from someone with my degree however I must admit, I think I learned just enough to pass the test but never really saw a use for it and therefore never really retained much of the material.
Now that i've matured some, I see the use for it all of the time. I KNOW that there are lots of places that math knowledge would improve my coding so i'm ready to relearn the old stuff and learn some new stuff.
What are your favorite resources out there? (Resources that can tie math into programming are even better if you have any!) Books? Websites? Blogs?
| 0
| 0
| 0
| 0
| 1
| 0
|
How can I calculate values between 0 and 1 from values between 0 and n. E.g. I have items with "click count" and want to get "importance" (a float between 0 and 1) from that.
My attempt: importance = 1-1/count
gives bad results, since the values don't distribute well…
| 0
| 0
| 0
| 0
| 1
| 0
|
I am working on a somewhat large corpus with articles numbering the tens of thousands. I am currently using PDFBox to extract with various success, and I am looking for a way to programatically check each file to see if the extraction was moderately successful or not. I'm currently thinking of running a spellchecker on each of them, but the language can differ, I am not yet sure which languages I'm dealing with. Natural language detection with scores may also be an idea.
Oh, and any method also has to play nice with Java, be fast and relatively quick to integrate.
| 0
| 1
| 0
| 0
| 0
| 0
|
I have the following code using C++:
double value = .3;
double result = cos(value);
When I look at the values in the locals window for "value" it shows 0.2999999999
Then, when I get the value of "result" I get: 0.95533648912560598
However, when I run cos(.3) on the computers calculator I get: .9999862922474
So clearly there is something that I am doing wrong.
Any thoughts on what might be causing the difference in results?
I am running Win XP on an Intel processor.
Thanks
| 0
| 0
| 0
| 0
| 1
| 0
|
I need to ask someone for a big favor. What you see in the code below are my calculations for train movement for a train game I am writing. There is a problem with the calculations, but I just can't seem to find it. The problem seems to be located in this code:
if($trainRow['direction'] == '-') {
$trackUnitCount = $routeData['track_unit_count'] - $trackUnitCount;
}
I will explain the exact problem in more depth later, but for now, I'd like to explain the train movement logic (the game may be found at http://apps.facebook.com/rails_across_europe):
The game board consists of a map of Europe containing cities. Cities are connected by routes. Routes have a starting city and an ending city. Routes are connected by track which is divided into track units. Each route has a given number of track units. A train may travel a route in either a positive (+) or negative (-) direction. If the city the train started at is the route's starting city, then the train is traveling in a positive direction. If the train's starting city is the route's ending city, then the direction is negative.
A train starts in a city and the user chooses a destination city to travel to. The train has a given number of track units it may travel in a single turn. If the train does not have enough track units to reach the destination city in a single turn, then the train's status is set to 'ENROUTE' and the train's current track unit is set to the track unit the train stopped on. The train's remaining track units is zero (since the train used all it's track units). If the train has more than enough track units to reach the destination, then the train stops at the destination and the train's status is set to 'ARRIVED'. The train's remaining track units is set to the trains starting track units minus the number of track units used to reach it's destination.
The player's turn will not end until his train's remaining track units reach zero, so once the player has finished his business at the current city, he will choose another city destination and the train will move it's remaining track units toward that city. If the train has more than enough track units remaining to reach that city, then it stops at the city and the track units traveled are subtracted from it's remaining track units. This goes on until the remaining track units reach zero.
The problem is that this code sets $trackUnitCount to zero, which then in turn sets the train's current track unit to zero, which indicates that the train has arrived at its destination city (which is incorrect). This results in the train hopping from one city to another without running out of track units remaining which should end the player's turn (before he arrived at the destination city)
If you can help me out with this, you are truly a cyber-saint :)
public function moveTrain($destCityId) {
require_once 'Train.php';
$trainModel = new Train();
require_once 'Route.php';
$routeModel = new Route();
$userNamespace = new Zend_Session_Namespace('User');
$gamePlayerId = $userNamespace->gamePlayerId;
$trainData = $trainModel->getTrain($gamePlayerId);
if($destCityId == $trainData['dest_city_id']) {
$originCityId = $trainData['origin_city_id'];
} else {
$originCityId = $trainData['dest_city_id'];
}
$routeId = $routeModel->getRouteIdByCityIds($originCityId, $destCityId);
$trainRow = array();
if($routeId !== null) {
$routeData = $routeModel->getRouteByCityIds($originCityId, $destCityId);
$trainRow['direction'] = $routeModel->getRouteTravelDirection($originCityId, $destCityId); //+
//$routeData['track_unit_count'] are the total number of track units in this route
//$trainData['track_unit'] is the track unit the train is currently stopped on
$trackUnitCount = $routeData['track_unit_count'] - $trainData['track_unit']; //6-3=3
//$trainData['track_units_remaining'] are the number of track units the train has left to move
$trackUnitsRemaining = $trainData['track_units_remaining'] - $trackUnitCount; //5-3=2
if($trackUnitsRemaining > 0) {
$trackUnitsTraveled = $trackUnitCount; //2
} else {
$trackUnitsTraveled = $trainData['track_units_remaining'];
$trackUnitsRemaining = 0;
}
//$trainRow = $trainData;
$trainRow['route_id'] = $routeId;
$trainRow['origin_city_id'] = $originCityId;
$trainRow['dest_city_id'] = $destCityId;
if($trainRow['direction'] == '+') {
$trainRowTrackUnit = $trackUnitsTraveled + $trainData['track_unit']; //2+3=5
} else {
$trainRowTrackUnit = $routeData['track_unit_count'] - $trainData['track_units_remaining'];
if($trainRowTrackUnit < 0) $trainRowTrackUnit = 0;
}
$trainRow['track_unit'] = $trainRowTrackUnit; //5
$trainRow['track_units_remaining'] = $trackUnitsRemaining; //2
$trainArrived = ($trainRowTrackUnit == 0 || $trainRowTrackUnit == $routeData['track_unit_count']);
$trainRow['status'] = ($trainArrived == true) ? 'ARRIVED' : 'ENROUTE';
$trainId = $trainModel->getTrainId($gamePlayerId);
$where = $trainModel->getAdapter()->quoteInto('id = ?', $trainId);
$trainModel->update($trainRow, $where);
}
return $trainRow;
}
| 0
| 0
| 0
| 0
| 1
| 0
|
I'm looking for an algorithm that would move a point around an arbitrary closed polygon that is not self-crossing in N time. For example, move a point smoothly around a circle in 3 seconds.
| 0
| 0
| 0
| 0
| 1
| 0
|
var = 8
itr 1:
var == 8 (8 * 1)
itr 2:
var == 24 (8 * 3)
itr 3:
var == 48 (8 * 6)
itr 4:
var == 80 (8 * 10)
itr 5:
var == 120 (8 * 15)
Pattern: (var * (last multiplier + current iteration))
Basically I want to get the result of formula(itr) without having to iterate up to itr.
| 0
| 0
| 0
| 0
| 1
| 0
|
I have a planar element in 3D space that I've rotated on the x, y and z axis. I'm positioning a 3D camera in front of the planar but I need to find a way to calculate the x, y, z of the camera.
I'm trying to figure out how to place the camera at x distance from the planes face. There's obviously a bit of trig involved but for the life of me can't figure it out. Gah.
Dave
| 0
| 0
| 0
| 0
| 1
| 0
|
I have a computer program that reads in an array of chars that operands and operators written in postfix notation. The program then scans through the array works out the result by using a stack as shown :
get next char in array until there are no more
if char is operand
push operand into stack
if char is operator
a = pop from stack
b = pop from stack
perform operation using a and b as arguments
push result
result = pop from stack
How do I prove by induction that this program correctly evaluates any postfix expression? (taken from exercise 4.16 Algorithms in Java (Sedgewick 2003))
| 0
| 0
| 0
| 0
| 1
| 0
|
How you could calculate size of brute force method dynamically? For example how many iterations and space would take if you printed all IPv6 addresses from 0:0:0:0:0:0:0:0 - ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff to file? The tricky parts are those when length of line varies. IP address is only example.
Idea is that you give the format and maximum lenghts of given parts. So if variable type is '%c' (char), and maxlen is 26 then iteration count is 26 and needed space in human format in text file is 26 + 26 (one char for separator)
def calculate(format, rules):
end = format
for i in rules:
(vartype, maxlen) = rules[i]
end = end.replace(i, vartype % maxlen)
start = format
for i in rules:
(vartype, maxlen) = rules[i]
minlen = 0
start = start.replace(i, vartype % minlen)
start_bytes = len(start)
end_bytes = len(end)
# how to add for example IPv4 calculations
# 0.0.0.0 - 9.9.9.9
# 10.10.10.10 - 99.99.99.99
# 100.100.100.100 - 255.255.255.255
iterations = 0
for i in rules:
if format.find(i) is not -1:
(vartype, maxlen) = rules[i]
if iterations == 0:
iterations = int(maxlen) + 1
else:
iterations *= int(maxlen) + 1
iterations -= 1
needed_space = 0
if start_bytes == end_bytes:
# +1 for separator (space / new line)
needed_space = (1 + start_bytes) * iterations
else:
needed_space = "How to calculate?"
return [iterations, needed_space, start, end, start_bytes, end_bytes]
if __name__ == '__main__':
# IPv4
print calculate(
"%a.%b.%c.%d",
{
'%a': ['%d', 255],
'%b': ['%d', 255],
'%c': ['%d', 255],
'%d': ['%d', 255]
},
)
# IPv4 zero filled version
print calculate(
"%a.%b.%c.%d",
{
'%a': ['%03d', 255],
'%b': ['%03d', 255],
'%c': ['%03d', 255],
'%d': ['%03d', 255]
},
)
# IPv6
print calculate(
"%a:%b:%c:%d:%e:%f:%g:%h",
{
'%a': ['%x', 65535],
'%b': ['%x', 65535],
'%c': ['%x', 65535],
'%d': ['%x', 65535],
'%e': ['%x', 65535],
'%f': ['%x', 65535],
'%g': ['%x', 65535],
'%h': ['%x', 65535]
},
)
# days in year, simulate with day numbers
print calculate(
"ddm%a", #ddmmyy
{
'%a': ['%03d', 365],
},
)
So for example:
1.2.3.4 takes 7 bytes
9.9.9.10 takes 8 bytes
1.1.1.100 takes 9 bytes
5.7.10.100 takes 10 bytes
128.1.1.1 takes 9 bytes
and so on
Example 0.0.0.0 - 10.10.10.10:
iterations = 0
needed_space = 0
for a in range(0, 11):
for b in range(0, 11):
for c in range(0, 11):
for d in range(0, 11):
line = "%d.%d.%d.%d
" % (a, b, c, d)
needed_space += len(line)
iterations += 1
print "iterations: %d needed_space: %d bytes" % (iterations, needed_space)
iterations: 14641 needed_space: 122452 bytes
Into
print calculate(
"%a.%b.%c.%d",
{
'%a': ['%d', 10],
'%b': ['%d', 10],
'%c': ['%d', 10],
'%d': ['%d', 10]
},
)
Result: [14641, 122452]
| 0
| 0
| 0
| 0
| 1
| 0
|
Let's say I have 20 players [names A .. T] in a tournament. The rules of the tournament state that each player plays every other player twice [A vs B, B vs A, A vs C .. etc]. With 20 players, there will be a total of 380 matches.
In each match, there are three possible outcomes - player 1 wins, player 2 wins, or draw. There's a betting exchange which, ahead of each match, quotes the probabilites of each outcome occuring; so you might have 40% player 1 wins, 30% player 2 wins, 30% draw [probabilities sum to 100%]; I store these probabilities ahead of each match.
Fast forward one quarter of the way through the tournament. I have collected probabilities for 95 games, with 285 still to go. What I want to know is -
Can the probability data from the 95 games be used to predict probabilities for the remaining 285 ?
For example, if I know A vs B and B vs C, can I use them to infer A vs C ?
And if so, how do I do it ?
| 0
| 1
| 0
| 0
| 0
| 0
|
I am writing a test tool which places a large amount of load on a network service. I would like this tool to start with little load and gradually increase over time. I am sure that there is some triganometry which can do this sort of calculation in one line of code but I am not a math guru (yet). Is there some sort of library (or simple algorithm) which can help with this calculation?
The code would ideally take a few arguments:
algorithm to use (determine how quickly the value increases
starting value
ending value (maximum)
time (amount of time between starting and ending value)
step (granularity in milliseconds)
So every [step] an event would be raised indicating what the value is at that point in time.
This is an ideal implementation though, so I am open to suggestion.
Any input would be greatly appreciated, thank you :)
EDIT:
Let me be more clear ... the amount which the value increases is not linear, it is a curve.
| 0
| 0
| 0
| 0
| 1
| 0
|
I have a logical statement that says "If everyone plays the game, we will have fun".
In formal logic we can write this as:
Let D mean the people playing.
Let G be the predicate for play the game.
Let F be the predicate for having fun.
Thus [VxeD, G(x)] -> [VyeD, F(y)]
V is the computer science symbol for universal quantification. E below is the existential quantifier.
I'm looking for a way to write a similar statement using only existential quantifiers. My best guess would be that we simply need to find a way to find the counter-example where it doesn't happen, thus negate the above.
The problem is negating it doesn't make sense. We get:
[VxeD, G(x)] ^ [EyeD, !L(y)]
It's not a proper statement since the universal is still in there though it is also equivalent. Thus I need to re-fabricate my statement to something like: VxeD, VyeD, G(x) ^ F(y) I would get ExeD, EyeD, !G(x) v !F(y) which would mean "There exists someone who doesn't learn or someone else who doesn't have fun" which doesn't seem correct to me.
Some guidance or clarification would be fantastic :-)
Thanks!
| 0
| 0
| 0
| 0
| 1
| 0
|
I am trying to calculate the vertices of a rotated rectangle (2D).
It's easy enough if the rectangle has not been rotated, I figured that part out.
If the rectangle has been rotated, I thought of two possible ways to calculate the vertices.
Figure out how to transform the vertices from local/object/model space (the ones I figured out below) to world space. I honestly have no clue, and if it is the best way then I feel like I would learn a lot from it if I could figure it out.
Use trig to somehow figure out where the endpoints of the rectangle are relative to the position of the rectangle in world space. This has been the way I have been trying to do up until now, I just haven't figured out how.
Here's the function that calculates the vertices thus far, thanks for any help
void Rect::calculateVertices()
{
if(m_orientation == 0) // if no rotation
{
setVertices(
&Vertex( (m_position.x - (m_width / 2) * m_scaleX), (m_position.y + (m_height / 2) * m_scaleY), m_position.z),
&Vertex( (m_position.x + (m_width / 2) * m_scaleX), (m_position.y + (m_height / 2) * m_scaleY), m_position.z),
&Vertex( (m_position.x + (m_width / 2) * m_scaleX), (m_position.y - (m_height / 2) * m_scaleY), m_position.z),
&Vertex( (m_position.x - (m_width / 2) * m_scaleX), (m_position.y - (m_height / 2) * m_scaleY), m_position.z) );
}
else
{
// if the rectangle has been rotated..
}
//GLfloat theta = RAD_TO_DEG( atan( ((m_width/2) * m_scaleX) / ((m_height / 2) * m_scaleY) ) );
//LOG->writeLn(&theta);
}
| 0
| 0
| 0
| 0
| 1
| 0
|
I am implementing a custo crypto library using the Diffie-Hellman protocol (yes, i know about rsa/ssl/and the likes - i am using it specific purposes) and so far it turned out better than i original expected - using GMP, it's very fast.
My question is, besides the obvious key exchange part, if this protocol can be used for digital signatures as well.
I have looked at quite a few resources online, but so far my search has been fruitless.
Is this at all possible?
Any (serious) ideas are welcome.
Update:
Thanks for the comments. And for the more curious people:
my DH implementation is meant - among other things - to distribute encrypted "resources" to client-side applications. both are, for the most part, my own code.
every client has a DH key pair, and i use it along with my server's public key to generate the shared keys. in turn, i use them for HMACs and symmetric encryption.
DH keys are built anywhere from 128 up to 512 bits, using safe primes as modulus.
I realize how "pure" D-H alone can't be used for signatures, i was hoping for something close to it (or as simple).
| 0
| 0
| 0
| 0
| 1
| 0
|
How can I do Mathematica-style
a = Table[2^(2 k) + 1, {k, 1, 3}]
Last[a], First[a]
Append[a,3]
in Octave?
| 0
| 0
| 0
| 0
| 1
| 0
|
I have a C# method and which accepts three string parameters. After converting them to decimal, I am trying to perform a simple math calculation. I don't understand, why isn't the result correct?
decimal d = MyFunction(x, y, z);
public decimal MyFunction(string x, string y, string z)
{
decimal dx = 0;
decimal dy = 0;
decimal dz = 0;
Decimal.TryParse(x, out dx);
Decimal.TryParse(y, out dy);
Decimal.TryParse(z, out dz);
decimal result = dx - dz + dy;
return result;
}
Thanks in advance.
| 0
| 0
| 0
| 0
| 1
| 0
|
I'm having an issue understanding the MixColumns step described here.
I know about diffusion and it all makes sense up the the point where it states that each column is treated as a polynomial and multiplied modulo over GF(2^8).
BUT..multiplying in GF(2^8). Although the domain is still the same, it is not reversible due to mod.... and it has to be reversible because that is the entire point of it.
As far as the first bit goes, my approach is taking A,B,C and D as the 4 bytes of a column and A1, A2, ..., A8 as the bits and E,F,G and H as the output bytes. I was going to set
E = A1,B2,C3,D4,A5,B6,C7,D8
F = D1,A2,B3,C4,D5,A6,B7,C8
G = C1,D2,A3,B4,C5,D6,A7,B8
H = B1,C2,D3,A4,B5,C6,D7,A8
And thus it is reversible, one-to-one, linear and distributive
It later states that it can be viewed as a matrix multiplication but as the elements of the matrix must be bytes and output as bytes then each element of the matrix must be modulo 256 and therefore not reversible and non linear.
Have I understood this wrong? I struggle with maths and am trying to understand what needs to be done so that I can convert it into logic.
| 0
| 0
| 0
| 0
| 1
| 0
|
I am looking for a method to determine if there is a solution to equations such as:
3n1+4n2+5n3=456, where n1,n2,n3 are positive integers.
Or more general: are there zero or positive integers n1,n2,n3... that solves the equation k1n1+k2n2+k3n3...=m where k1,k2,k3... and m are known positive integers.
I don't need to find a solution - just to determine if a solution exist.
Edit:
Concerning the practical use of this algorithm:
In a communication library, I want to decide if a given message is valid according to its size, before handling the message.
For example: I know that a message contains zero-or-more 3-bytes elements, zero-or-more 4-bytes elements, and zero-or-more 5-bytes elements. I received a message of 456 bytes, and I want to determine its validity before further inspecting its content.
Of course the header of the message contains the number of elements of each type, but I want to make a first-inspection in the communication-library level by passing something like pair<MsgType,vector<3,4,5>>.
| 0
| 0
| 0
| 0
| 1
| 0
|
With a sine input, I tried to modify it's frequency cutting some lower frequencies in the spectrum, shifting the main frequency towards zero. As the signal is not fftshifted I tried to do that by eliminating some samples at the begin and at the end of the fft vector:
interval = 1;
samplingFrequency = 44100;
signalFrequency = 440;
sampleDuration = 1 / samplingFrequency;
timespan = 1 : sampleDuration : (1 + interval);
original = sin(2 * pi * signalFrequency * timespan);
fourierTransform = fft(original);
frequencyCut = 10; %% Hertz
frequencyCut = floor(frequencyCut * (length(pattern) / samplingFrequency) / 4); %% Samples
maxFrequency = length(fourierTransform) - (2 * frequencyCut);
signal = ifft(fourierTransform(frequencyCut + 1:maxFrequency), 'symmetric');
But it didn't work as expected. I also tried to remove the center part of the spectrum, but it wielded a higher frequency sine wave too.
How to make it right?
| 0
| 0
| 0
| 0
| 1
| 0
|
I have two sets of statistics generated from processing. The data from the processing can be a large amount of results so I would rather not have to store all of the data to recalculate the additional data later on.
Say I have two sets of statistics that describe two different sessions of runs over a process.
Each set contains
Statistics : { mean, median, standard deviation, runs on process}
How would I merge the two's median, and standard deviation to get a combined summary of the two describing sets of statistics.
Remember, I can't preserve both sets of data that the statistics are describing.
| 0
| 0
| 0
| 0
| 1
| 0
|
The problem is to teach computer to do addition.
Computers have a knowledge of a numbers: he "knows" that after 1 goes 2, after 2 goes 3 and so on. Having that data computer can easily get next number.
Next, computer have the knowledge that x+0=x and x+(y+1)=(x+1)+y. This axioms let computer to do addition. For example, to add 5 and 3, computer makes following: 5+3 = 5+(2+1) = (5+1)+2 = 6+2 = 6+(1+1) = (6+1)+1 = 7+1 = 8.
But this is too long to add numbers in such way. The problem is to develop program which can improve this way of addition using the rules of mathematics and logic. The goal should be that addition must be executed in O(log(N)) time, not O(N) time, N is magnitude of added numbers.
Does this program have any science value? Is there any program that can do such things?
| 0
| 1
| 0
| 0
| 0
| 0
|
I want to draw a graph that will be something like this:
alt text http://img25.imageshack.us/img25/9786/problemo.png
You can see 3 pathes: a, b & c. How can I change position of elements (1,2,3...,9) to make long of the path as short as possible? I mean this lines should be as short as possible.
Im very interested in it becouse I am drawing a graph with question, some kind of infographic like 'follow the lines to know the answer'. I know that its a bit about graph theory... so if its too hard, do you know if Is there any program for linux to compact stuff like this?
For example program should work like this:
In input it should get 3 pathes
a='1,5,7,8,4,2,6'
b='4,2,3,6,9,8,5'
c='7,9'
And in output in should be coordinates of this elements.
| 0
| 0
| 0
| 0
| 1
| 0
|
My inner loop contains a calculation that profiling shows to be problematic.
The idea is to take a greyscale pixel x (0 <= x <= 1), and "increase its contrast". My requirements are fairly loose, just the following:
for x < .5, 0 <= f(x) < x
for x > .5, x < f(x) <= 1
f(0) = 0
f(x) = 1 - f(1 - x), i.e. it should be "symmetric"
Preferably, the function should be smooth.
So the graph must look something like this:
.
I have two implementations (their results differ but both are conformant):
float cosContrastize(float i) {
return .5 - cos(x * pi) / 2;
}
float mulContrastize(float i) {
if (i < .5) return i * i * 2;
i = 1 - i;
return 1 - i * i * 2;
}
So I request either a microoptimization for one of these implementations, or an original, faster formula of your own.
Maybe one of you can even twiddle the bits ;)
| 0
| 0
| 0
| 0
| 1
| 0
|
I need(for rapid prototyping and libraries integration) something like this(extensions for usual arrays)
double[] d;
d.SetRow(1,{ 1.1 , 2.0 ,3.3});
var r = d.GetRow(1);
d = d.AppendRight(new int[]{1,2,3});
...
Does exist such thing anywhere?
On may be anybody implemented it so I do not need do i for me myself?
| 0
| 0
| 0
| 0
| 1
| 0
|
I need to write some mathematical expressions (like a matrix and mathematical variables...) into my GUI.
The MFC static control is very limited on this issue. Especially for the math. symbols.
Is there any control or other way to make this happen?
| 0
| 0
| 0
| 0
| 1
| 0
|
Recently I've been thinking about finite state machines (FSMs), and how I would implement them in software (programming language doesn't matter).
My understanding is that deterministic state machines are in widespread use (parses/lexers, compilers and so on), but what's the matter with non-deterministic state machines?
I know that is possible to convert all non-deterministic state machines to deterministic ones (even programmatically). That's not my point. I also imagine that non-deterministic state machines are much more complicated to implement.
Anyway, does it make any sense to implement a non-deterministic state machine? Are there any special applications I don't know about?
What could be the reasons to do that? Maybe optimized and specialized non-deterministic state machines are faster?
| 0
| 0
| 0
| 0
| 1
| 0
|
A developer I am working with is developing a program that analyzes images of pavement to find cracks in the pavement. For every crack his program finds, it produces an entry in a file that tells me which pixels make up that particular crack. There are two problems with his software though:
1) It produces several false positives
2) If he finds a crack, he only finds small sections of it and denotes those sections as being separate cracks.
My job is to write software that will read this data, analyze it, and tell the difference between false-positives and actual cracks. I also need to determine how to group together all the small sections of a crack as one.
I have tried various ways of filtering the data to eliminate false-positives, and have been using neural networks to a limited degree of success to group cracks together. I understand there will be error, but as of now, there is just too much error. Does anyone have any insight for a non-AI expert as to the best way to accomplish my task or learn more about it? What kinds of books should I read, or what kind of classes should I take?
EDIT My question is more about how to notice patterns in my coworker's data and identify those patterns as actual cracks. It's the higher-level logic that I'm concerned with, not so much the low-level logic.
EDIT In all actuality, it would take AT LEAST 20 sample images to give an accurate representation of the data I'm working with. It varies a lot. But I do have a sample here, here, and here. These images have already been processed by my coworker's process. The red, blue, and green data is what I have to classify (red stands for dark crack, blue stands for light crack, and green stands for a wide/sealed crack).
| 0
| 1
| 0
| 0
| 0
| 0
|
I'm trying to understang how to use icu::BreakIterator to find specific words.
For example I have following sentence:
To be or not to be? That is the question...
Word instance of break iterator would put breaks there:
|To| |be| |or| |not| |to| |be|?| |That| |is| |the| |question|.|.|.|
Now, not every pair of break points is actual word.
In derived class icu::RuleBasedBreakIterator there is a "getRuleStatus()" that returns some kind of information about break, and it gives "Word status at following points (marked "/")"
|To/ |be/ |or/ |not/ |to/ |be/?| |That/ |is/ |the/ |question/.|.|.|
But... It all depends on specific rules, and there is absolutely no documentation to understand it (unless I just try), but what would happend with different locales and languages where dictionaries are used? what happens with backware iteration?
Is there any way to get "Begin of Word" or "End of Word" information like in Qt QTextBoundaryFinder: http://qt.nokia.com/doc/4.5/qtextboundaryfinder.html#BoundaryReason-enum?
How should I solve such problem in ICU correctly?
| 0
| 1
| 0
| 0
| 0
| 0
|
Today, I came across quite strange problem. I needed to calculate string length of a number, so I came up with this solution
// say the number is 1000
(int)(log(1000)/log(10)) + 1
This is based on mathematical formula
log10x = lognx/logn10 (explained here)
But I found out, that in C,
(int)(log(1000)/log(10)) + 1
is NOT equal to
(int) log10(1000) + 1
but it should be.
I even tried the same thing in Java with this code
(int) (Math.log(1000) / Math.log(10)) + 1
(int) Math.log10(1000) + 1
but it behave the same wrong way.
The story continues. After executing this code
for (int i = 10; i < 10000000; i *= 10) {
System.out.println(((int) (Math.log10(i)) + 1) +
" " + ((int) (Math.log(i) / Math.log(10)) + 1));
}
I get
2 2
3 3
4 3 // here second method produces wrong result for 1000
5 5
6 6
7 6 // here again
So the bug seems to occur on every multiple of 1000.
I showed this to my C teacher, and he said that it might be caused by some type conversion error during log division, but he didn't know why.
So my questions are
Why isn't (int) (Math.log(1000) / Math.log(10)) + 1 equal to (int) Math.log10(1000) + 1
, while it should be, according to the math.
Why is it wrong only for multiples of 1000?
edit: It is not rounding error, because
Math.floor(Math.log10(i)) + 1
Math.floor(Math.log(i) / Math.log(10)) + 1
produce same, wrong output
2 2
3 3
4 3
5 5
6 6
7 6
edit2: I have to round down, because I want to know the number of digits.
log10(999) + 1 = 3.9995654882259823
log10(1000) + 1 = 4.0
If I just round, I get same result (4), which is wrong for 999, because it has 3 digits.
| 0
| 0
| 0
| 0
| 1
| 0
|
I have an array of Points. I KNOW that these points represent many lines in my page.
How can I find them? Do I need to find the spacing between clouds of points?
Thanks
Jonathan
| 0
| 0
| 0
| 0
| 1
| 0
|
I have 3 Vectors, Up Right and Front that represent a direction.
I need to convert these into an XYZ angle (3 floats) so i can use with glRotatef()
Please help
[EDIT]
Its not rendering properly. can you see if its anything blatant here: pastebin.com/f6683492d
| 0
| 0
| 0
| 0
| 1
| 0
|
I have a function to round a number given to the function to the nearest whole pence.
<script type='text/javascript'>
Math.roundNumber = function(a,b){
if(!isNaN(parseInt(a))){
c = Math.pow(10,b);
return (Math.round(a*c)/c);
}
return false;
}
</script>
however it has come to my attention that the said number inputted into the function must only be rounded up to the nearest one pence however it must be rounded to two decimal places.
E.G.
15.236562213541684 would = 15.24
9846.65456169846 would = 9846.66
I thought it would just be a case of changing
return (Math.round(ac)/c);
To
return (Math.ceil(ac)/c);
Obviously I was very wrong.
Any help on this matter?
** EDIT **
Here is the formula that I'm trying to achieve maybe it'll help
a = intrest price
b = terms
c = a/b
d = c*(b-1)
e = a-d
so for example
a = 295.30
b = 156
c = 295.30/156 = 1.90 (rounded up to nearest decimal as above)
d = 1.90 * (b-1) = 294.50
e = 295.30 - 294.50 = 0.80
can anyone right a function to do the above?
Here is a link to the current code i have including the formula... its a very old formula that I made when I first started JavaScript (which is a while ago now) however I'm still no better now as I was back then.
Can anyone clean it up to see if they can see why its not working to match the function above?
| 0
| 0
| 0
| 0
| 1
| 0
|
I just wondered how it is possible to write a user-defined square root function (sqrt) in a way that it interacts properly with F#'s unit system.
What it should be like:
let sqrt (x : float<'u ^ 2>) =
let x' = x / 1.0<'u ^ 2> // Delete unit
(x ** 0.5) * 1.0<'u> // Reassign unit
But this is disallowed due to nonzero constants not being allowed to have generic units.
Is there a way to write this function? With the builtin sqrt it works fine, so what magic does it perform?
| 0
| 0
| 0
| 0
| 1
| 0
|
Not sure if that is the right way to ask this or not but here is the problem.
Given a latitude of 26.746346081599476, how do I find the number 26.75 as the 16th greater than the number and 26.6875 as the 16th lower than the number?
26.0
26.0625
26.125
26.1875
26.25
26.3125
26.375
26.4375
26.5
26.5625
26.625
26.6875
My Number: 26.746346081599476
26.75
26.8125
26.875
26.9375
27.0
I'm using JavaScript so an answer in that would be helpful but not necessary. I could brute force it but I'm looking for the elegant way to do it.
The bigger picture is that I want to create standard tiles for a mapping application I'm working on. We are using Bing maps and I am loading data on-demand, every time the user pans or zooms in. It would be nice to take advantage of server side caching for these requests so if I standardize the queries sent to the server I would get some cache hits. If I don't standardize the requests to the server it is highly unlikely that the same user would be viewing the exact some location at the same time.
So there is a higher chance of getting cache hits with:
/path/data.json?tl=26.6875,-80.6875&br=26.75,-80.75
than with:
/path/data.json?tl=26.74946187679896,-80.10930061340332&br=26.743234270702878,-80.09607195854187
Any outside the box answers are welcome as well.
| 0
| 0
| 0
| 0
| 1
| 0
|
Given a set of n numbers (1 <= n <= 100) where each number is an integer between 1 and 450,we need to distribute those set of numbers into two sets A and B, such that the following two cases hold true:
The total numbers in each set differ by at most 1.
The sum of all the numbers in A is as nearly equal as possible to the sum of all the numbers in B i.e. the distribution should be fair.
Can someone please suggest an efficient algorithm for solving the above problem ?
Thank You.
| 0
| 0
| 0
| 0
| 1
| 0
|
Consider a sales department that sets a sales goal for each day. The total goal isn't important, but the overage or underage is. For example, if Monday of week 1 has a goal of 50 and we sell 60, that day gets a score of +10. On Tuesday, our goal is 48 and we sell 46 for a score of -2. At the end of the week, we score the week like this:
[0,0]=10,[0,1]=-2,[0,2]=1,[0,3]=7,[0,4]=6
In this example, both Monday (0,0) and Thursday and Friday (0,3 and 0,4) are "hot"
If we look at the results from week 2, we see:
[1,0]=-4,[1,1]=2,[1,2]=-1,[1,3]=4,[1,4]=5
For week 2, the end of the week is hot, and Tuesday is warm.
Next, if we compare weeks one and two, we see that the end of the week tends to be better than the first part of the week. So, now let's add weeks 3 and 4:
[0,0]=10,[0,1]=-2,[0,2]=1,[0,3]=7,[0,4]=6
[1,0]=-4,[1,1]=2,[1,2]=-1,[1,3]=4,[1,4]=5
[2,0]=-8,[2,1]=-2,[2,2]=-1,[2,3]=2,[2,4]=3
[3,0]=2,[3,1]=3,[3,2]=4,[3,3]=7,[3,4]=9
From this, we see that the end of the week is better theory holds true. But we also see that end of the month is better than the start. Of course, we would want to next compare this month with next month, or compare a group of months for quarterly or annual results.
I'm not a math or stats guy, but I'm pretty sure there are algorithms designed for this type of problem. Since I don't have a math background (and don't remember any algebra from my earlier days), where would I look for help? Does this type of "hotspot" logic have a name? Are there formulas or algorithms that can slice and dice and compare multidimensional arrays?
Any help, pointers or advice is appreciated!
| 0
| 0
| 0
| 0
| 1
| 0
|
I don't have so much a question about how to program something, but rather I'm looking for information on a specific programming language that I can't seem to find anywhere. It seems to be referenced in a few papers I'm looking at. The name of the language is "NeuPro" - it would be for working with Neural Networks and appears to have a syntax very similar to prolog. Anyway, if someone could shed some light of provide a reference I can work on that would be great.
| 0
| 1
| 0
| 0
| 0
| 0
|
If I have the coordinates of a point (lat lon) and the azimuth angle how can I calculate what points are at "the end' of a distance of 10 miles.
Ex. I am watching North , I know I am at a certain point ... At 10 miles apart what coordinates has that geo point ?
| 0
| 0
| 0
| 0
| 1
| 0
|
I have 2 arrays of ints I am using to create a polygon (that looks like a fish). What do I need to do to the arrays to flip the polygon horizontally?
x = new int[]
{ 0, 18, 24, 30, 48, 60, 60, 54, 60, 48, 30, 24, 0 };
y = new int[]
{ 0, 18, 6, 0, 0, 12, 18, 24, 24, 36, 36, 30, 36 };
| 0
| 0
| 0
| 0
| 1
| 0
|
I am looking for a Chess AI that can be run on Google App Engine. Most chess AI's seem to be written in C and so can not be run on the GAE. It needs to be strong enough to beat a casual player, but efficient enough that it can calculate a move within a single request (less than 10 secs).
Ideally it would be written in Python for easier integration with existing code.
I came across a few promising projects but they don't look mature:
http://code.google.com/p/chess-free
http://mariobalibrera.com/mics/ai.html
| 0
| 1
| 0
| 0
| 0
| 0
|
It's been a while since my math in university, and now I've come to need it like I never thought i would.
So, this is what I want to achieve:
Having a set of 3D points (geographical points, latitude and longitude, altitude doesn't matter), I want to display them on a screen, considering the direction I want to take into account.
This is going to be used along with a camera and a compass , so when I point the camera to the North, I want to display on my computer the points that the camera should "see". It's a kind of Augmented Reality.
Basically what (i think) i need is a way of transforming the 3D points viewed from above (like viewing the points on google maps) into a set of 3d Points viewed from a side.
| 0
| 0
| 0
| 0
| 1
| 0
|
Doing a couple rotations in Matlab, one which is rotation about the y-axis, however online I've found two different answers: here and here. Which is correct, if both how does one get to the other?
| 0
| 0
| 0
| 0
| 1
| 0
|
I'm having trouble calculating roots of rather large numbers using bc_math, example:
- pow(2, 2) // 4, power correct
- pow(4, 0.5) // 2, square root correct
- bcpow(2, 2) // 4, power correct
- bcpow(4, 0.5) // 1, square root INCORRECT
Does anybody knows how I can circumvent this? gmp_pow() also doesn't work.
| 0
| 0
| 0
| 0
| 1
| 0
|
As you may be able to tell from this screenshot, I am trying to make a physics engine for a platformer I am working on, but I have run into a definite problem: I need to be able to find out the angle of any one of the triangles that you can see make up this mesh, so that I can work out the rotation and therefore angular acceleration of the player on that triangle.
I can use an algorithm that I created to find the locations of all 3 points of any triangle that the player is in contact with, but I don't know how to use those points to work out the rotation of the triangle.
By the rotation, I mean the direction of the normal away from the centre of the face, i.e., the angle at which a person would be leaning if they stood on that surface. Can someone come up with a series of equations that will allow for this problem to be solved?
| 0
| 0
| 0
| 0
| 1
| 0
|
Further to: Choosing an attractive linear scale for a graph's Y Axis
And what to do when some of the points
are negative?
I believe this part of the question was not answered but it seems I can't comment or extend that question so I've created a new one
Values -100, 0, 100 with 5 ticks:
lower bound = -100
upper bound = 100
range = 100--100 = 200
tick range = 40
Divide by 10^2 for 0.4, translates to 0.4, which gives (multiplied by 10^2) 40.
new lower bound = 40 * round(-100/40) = -80
new upper bound = 40 * round(1+100/40) = 120
or
new lower bound = 40 * floor(-100/40) = -120
new upper bound = 40 * floor(1+100/40) = 120
Now the range has been increased to 240 (an extra tick!), with 5 ticks at 40 each.
it will take 6 steps to fill the new range!
Solution?
| 0
| 0
| 0
| 0
| 1
| 0
|
What kind of algorithm would be good to cluster and rank blogs in logical communities (tech, entertainment, etc...)?
An algorithm to cluster and rank blog posts would be even better.
Answers accepted are algorithms, pseudo-code, java code or links to explanations on particular algorithms.
Update:
So, it seems I would like something in the category of Partional Clustering based, mostly, on textual features.
| 0
| 0
| 0
| 1
| 0
| 0
|
I'd like something that converts a simple calculator like ascii math syntax to mathML.
I found this: http://www1.chapman.edu/~jipsen/mathml/asciimath.html
But I don't understand how to use it.. I'd like to make it work from the command line for example, so that I feed it some math formula and get back the mathMl version.
How could I do it? Is there any other program like this, maybe in a less browser oriented language than javascript?
| 0
| 0
| 0
| 0
| 1
| 0
|
I run a website that allows users to write blog-post, I would really like to summarize the written content and use it to fill the <meta name="description".../>-tag for example.
What methods can I employ to automatically summarize/describe the contents of user generated content?
Are there any (preferably free) methods out there that have solved this problem?
(I've seen other websites just copy the first 100 or so words but this strikes me as a sub-optimal solution.)
| 0
| 1
| 0
| 0
| 0
| 0
|
I wrote some code that looks like this:
def get(x, y)
@cachedResults.set(x,y, Math.hypot(x, y)) if @cachedResults.get(x,y).nil?
@cachedResults.get(x,y)
end
Where @cachedResults contained a 2D Array class i wrote (in a few minutes) and the purpose of this function is to make sure that I never have to call Math.hypot twice for any given (x,y). [This could be optimised further using symmetry and other things but whatever]
So I called the function and let it run 160000 times; it ran in just over 15 seconds. Then, to see how much faster it was than the non Memoized version, i changed the code to this:
def get(x, y)
Math.hypot(x, y)
end
And, much to my surprise, it took just over 15 seconds to run again. The exact same time. So my question is, are the maths functions in ruby naturally Memoized? And, if so, to what extent is ruby Memoized?
(If not then why do you think I am getting this result consistently?)
| 0
| 0
| 0
| 0
| 1
| 0
|
I have a point at 0,0,0
I rotate the point 30 deg around the Y axis, then 30 deg around the X axis.
I then want to move the point 10 units forward.
I know how to work out the new X and Y position
MovementX = cos(angle) * MoveDistance;
MovementY = sin(angle) * MoveDistance;
But then I realised that these values will change because of Z, won't they?
How do I work out Z and have I worked out X and Y correctly?
Thanks!
| 0
| 0
| 0
| 0
| 1
| 0
|
If I have a Catmull-Rom spline of a certain length how can I calculate its position at a certain distance? Typically to calculate the point in a catmull rom spline you input a value between 0 and 1 to get its position via proportions, how can I do this for distances? For example if my spline is 30 units long how can I get its position at distance 8?
The reason I ask is because it seems with catmull rom splines giving points in the [0,1] domain does not guarantee that it will give you the point at that distance into the spline, for example if I input 0.5 into a catmull romspline of length 30 it does not mean I'll get the position at the distance of 15 of the spline unless the spline itself is in effect a straight line..
| 0
| 0
| 0
| 0
| 1
| 0
|
i have a mysql table for uk people that includes:
postcode beginning (i.e. BB2)
latitude (int)
longitude (int)
range (int, in miles, 1-20)
http://www.easypeasy.com/guides/article.php?article=64 - theres the article for the sql file i based my table on
now it says i can use Pythagoras theorem to calculate distances based on longitude and latitude.
so lets say i wanted to select all the people who are in range (based on the 1-20 they enter in the range field) of a postcode beginning i search for
for example, lets say i search for "BB2", i want a query that will select all of the people whose postcode beginning is "BB2", AND all the people within range of BB2 (going by the 1-20 mile range in their database field).
can some math whiz help me out?
| 0
| 0
| 0
| 0
| 1
| 0
|
I have two
double a, b;
I know that the following is true
-1 <= a/b <= 1
however b can be arbitrarily small. When I do this naively and just compute the value
a/b
the condition specified above does not hold in some cases and I get values like much greater than 1 in absolute value (like 13 or 14.)
How can I ensure that when I divide by b, I get a value such that the condition mentioned above can be enforced. In the case where I can not guarantee this I am happy to set the computed value a/b to 0.
| 0
| 0
| 0
| 0
| 1
| 0
|
I would like to know how to optimize the following SQL to let my server load faster and take low usage?
I need to calculate the radius distance for a US ZIP Code to get the result, such as 50 miles from a particular ZIP Code ( using latitude and longitude to calculate ) and to getting how many other data ( e.g. others ZIP Code ) from my database.
Once I get the result ( for example got 350 rows of different ZIP Codes within 50 miles from particular ZIP Code ), I need to passing them into another query to count the total rows and display it in simple and one result for me to read. Here is an example of my query:
SELECT count(*)
FROM
( SELECT b.ID, ROUND((acos(sin(3.142/180*32.91336) * sin(3.142/180*z.latitude) + cos(3.142/180*32.91336) * cos(3.142/180*z.latitude) * cos((3.142/180*z.longitude) - (3.142/180*-85.93836))) * 3959),2) AS distance
FROM zipcode2business.accountants b LEFT JOIN zipcodeworld.storelocator_us z ON b.ZIPCODE = z.ZIP_CODE
WHERE z.latitude != 32.91336 AND z.longitude != -85.93836
AND b.STATE='AL'
HAVING distance between 0 AND 50)
as total;
Hopefully I didn't done wrongly, it displays correct result ( 350 rows ), but I need an optimized way to runs it because this SQL gave me a high CPU usage to load.
When I do EXPLAIN for this query, it display following:
+----+-------------+-------+--------+------------------+---------+---------+----------------------------+------+------------------------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+-------------+-------+--------+------------------+---------+---------+----------------------------+------+------------------------------+
| 1 | PRIMARY | NULL | NULL | NULL | NULL | NULL | NULL | NULL | Select tables optimized away |
| 2 | DERIVED | b | ref | ZIPCODE,STATE | STATE | 4 | | 3900 | Using where |
| 2 | DERIVED | z | eq_ref | PRIMARY,LAT_LONG | PRIMARY | 9 | zipcode2business.b.ZIPCODE | 1 | Using where |
+----+-------------+-------+--------+------------------+---------+---------+----------------------------+------+------------------------------+
3 rows in set (0.20 sec)
Now, from above explanation, the "Select tables optimized away" in EXTRA is a good thing?
Please kindly show me one most perfect optimization SQL to do this query.
| 0
| 0
| 0
| 0
| 1
| 0
|
What is problem with follwoing code?
I am getting very strange results. Do I missing something?
proc Dot {vec1 vec2} {
set ret [expr ([lindex $vec1 0]*[lindex $vec2 0])+([lindex $vec1 1]*[lindex $vec2 1])+([lindex $vec1 2]*[lindex $vec2 2])]
}
proc FindInterSectPoint_LineAndPlane {normalVectorPlane basePoint refPoint topoint} {
foreach {norm1 norm2 norm3} $normalVectorPlane {break}
foreach {xB yB zB} $basePoint {break}
foreach {xb yb zb} $refPoint {break}
foreach {xa ya za} $topoint {break}
set vecL1 [expr $xb-$xa]
set vecL2 [expr $yb-$ya]
set vecL3 [expr $zb-$za]
set direction [expr -($norm1*$xB)+($norm2*$yB)+($norm3*$zB)]
set d [expr -(($vecL1*$xb)+($vecL2*$yb)+($vecL3*$zb)+$direction)]
set n [Dot $normalVectorPlane [list $vecL1 $vecL2 $vecL3] ]
if {$n == 0} {
return "line on parallel to plane"; # line on plane
}
set s [expr $d/($n*1.000)]
if {$s > 0 && $s < 1} {
set ret "intersection occurs between the two end points"
} elseif {$s == 0} {
set ret "intersection falls on the first end point"
} elseif {$s == 1} {
set ret "intersection falls on the second end point"
} elseif {$s > 1} {
set ret "intersection occurs beyond second end Point"
} elseif {$s < 0} {
set ret "intersection happens before 1st end point"
} else {
set ret "error"
}
set x [expr [lindex $refPoint 0]+($s*$vecL1)]
set y [expr [lindex $refPoint 1]+($s*$vecL2)]
set z [expr [lindex $refPoint 2]+($s*$vecL3)]
lappend ret "$x $y $z n=$n d=$d s=$s"
}
Output:
%FindInterSectPoint_LineAndPlane {0 0 1} {0 0 0} {0 0 0} {1 2 3}
intersection falls on the first end point {0.0 0.0 0.0 n=-3 d=0 s=-0.0}
%FindInterSectPoint_LineAndPlane {1 0 0} {0 0 0} {0 0 1} {0 0 0}
line on parallel to plane
%FindInterSectPoint_LineAndPlane {1 0 0} {0 0 0} {0 0 1} {0 0 5}
line on parallel to plane
%FindInterSectPoint_LineAndPlane {0 0 1} {0 0 0} {1 1 1} {2 2 2}
intersection happens before 1st end point {4.0 4.0 4.0 n=-1 d=3 s=-3.0}
%FindInterSectPoint_LineAndPlane {0 0 1} {0 0 0} {-1 -1 -1} {2 2 2}
intersection occurs beyond second end Point {-10.0 -10.0 -10.0 n=-3 d=-9 s=3.0}
| 0
| 0
| 0
| 0
| 1
| 0
|
I'm currently working on replicating some of the functionality of Matlab's regionprops function in Octave. However, I have a bit of a hangup on a subset of the functionality. The 'Eccentricity', 'MajorAxisLength', 'MinorAxisLength' and 'Orientation' properties are my sticking point. In the documentation, they all derive from "...the ellipse that has the same second-moments as the region."
So my question is, what are these second-moments, and how do I find them?
I was looking at this link:
http://en.wikipedia.org/wiki/Image_moments
Honestly, it's just left me more confused. Can anyone point me towards something a little more beginner friendly? Thanks.
| 0
| 0
| 0
| 0
| 1
| 0
|
I am working on a WISE Installer that needs to run on Java Version 1.5 or greater. So I have it read the registry for the Java Runtime Environment and get the "CurrentVersion" variable - for example 1.6, and place it in a WISE property.
I am attempting to build a Launch Condition that prevents the Installer from continuing if it is run on a system with an older version of Java. For this I attempted to have it check my variable i.e.: (if) JAVAINSTALLED < 1.5 (then error out). When I try to build this condition I get back an error message "real numbers not supported". It apparently works when you compare it to a whole number (as there are other launch conditions that do this)
So I am wondering what the best way to handle this is. I have thought of the idea of taking the variable and multiplying it by 10 so I can check for < 15 instead, but I do not know if this would work and not sure how to implement math functions with the limited control I have in WISE.
any ideas are greatly appreciated. thanks!
(Note: Using Wise Installation Studio version 7)
| 0
| 0
| 0
| 0
| 1
| 0
|
I'm trying to reduce a high-dimension dataset to 2-D. However, I don't have access to the whole dataset upfront. So, I'd like to generate a function that takes an N-dimensional vector and returns a 2-dimensional vector, such that if I give it to vectors that are close in N-dimensional space, the results are close in 2-dimensional space.
I thought SVD was the answer I needed, but I can't make it work.
For simplicity, let N=3 and suppose I have 15 datapoints. If I have all the data upfront in a 15x3 matrix X, then:
[U, S, V] = svd(X);
s = S; %s is a the reduced version of S, since matlab is case-sensitive.
s(3:end,3:end)=0;
Y=U*s;
Y=Y(1:2,:);
does what I want. But suppose I get a new datapoint, A, a 1x3 vector. Is there a way to use U, S, or V to turn A into the appropriate 1x2 vector?
If SVD is a lost cause, can someone tell me what I should be doing instead?
Note: This is Matlab code, but I don't care if the answer is C, Java, or just math. If you can't read Matlab, ask and I'll clarify.
| 0
| 0
| 0
| 0
| 1
| 0
|
I'm in need of a lightweight library for 2d & 3d vectors and 3x3 & 4x4 matrices. In basic C.
Just so I don't reinvent the wheel suboptimally.
Any suggestions?
| 0
| 0
| 0
| 0
| 1
| 0
|
I have thought of some heuristics for a big (higher dimensions) tic-tac-toe game. How do I check which of them are actually consistent?
What is meant by consistency anyways?
| 0
| 1
| 0
| 0
| 0
| 0
|
In Artificial Intelligence we studied the backtracking algorithm. Here is the pseudocode our book offers:
function backtrack;
begin
SL:= [Start]; NSL := [Start]; DE := [] CS := Start;
while NSL != [] do
begin
if CS = goal (or meets goal description)
then return SL;
if CS has no children (excluding nodes already on DE, SL, and NSL)
then begin
while SL is not empty and CS = the first element of SL do
begin
add CS to DE
remove first element froM SL;
remove first element from NSL;
CS := first element of NSL;
end
add CS to SL;
end
else begin
place children of CS (except nodes already on DE, SL or NSL) on NSL;
CS := first element of NSL;
add CS to SL;
end
end
return FAIL;
end
SL: the state list, lists the states in the current path being
tried.
NSL: the new state list, contains nodes awaiting evaluation.
DE: dead ends, lists states whose descendants have failed to contain a
goal node.
CS: the current state
I understand this and have not only hand run the algorithm but written programs in class that utilize it as well.
However, now we have been tasked with modifying it so it can be run on "and/or" graphs.
(Example and/or graph)
alt text http://starbase.trincoll.edu/~ram/cpsc352/notes/gifs/whereisfred.gif
The textbook had the following sentence talking about backtracking and/or graphs:
"And/or graph search requires only
slightly more record keeping than
search in regular graphs, an example
of which was the backtrack algorithm.
The or descendants are checked as
they were in backtrack: once a path is
found connecting a goal to a start
node along or nodes, the problem
will be solved. If a path leads to a
failure, the algorithm may backtrack
and try another branch. In searching
and nodes, however, all of the and descendants of a node must be solved (or proved true) to solve the
parent node.
While I understand what "and/or" graphs are, I'm having trouble modifying the above backtracking algorithm so that it works with "and/or" graphs. As the book says, if they are "OR" nodes, it should proceed as normal but what I'm having difficulty with are "and" nodes. Do I need to do something like:
if CS has children and is "AND" node then
resolve all children of CS
if children are all true, add children to NSL
else backtrack?
This is as close as I can get conceptually in my head, but it still doesn't feel right. Can anyone help me flesh it out a little further?
| 0
| 1
| 0
| 0
| 0
| 0
|
I would like my C function to efficiently compute the high 64 bits of the product of two 64 bit signed ints. I know how to do this in x86-64 assembly, with imulq and pulling the result out of %rdx. But I'm at a loss for how to write this in C at all, let alone coax the compiler to do it efficiently.
Does anyone have any suggestions for writing this in C? This is performance sensitive, so "manual methods" (like Russian Peasant, or bignum libraries) are out.
This dorky inline assembly function I wrote works and is roughly the codegen I'm after:
static long mull_hi(long inp1, long inp2) {
long output = -1;
__asm__("movq %[inp1], %%rax;"
"imulq %[inp2];"
"movq %%rdx, %[output];"
: [output] "=r" (output)
: [inp1] "r" (inp1), [inp2] "r" (inp2)
:"%rax", "%rdx");
return output;
}
| 0
| 0
| 0
| 0
| 1
| 0
|
I want to see the values of the function y(x) with different values of x, where y(x) < 5:
y = abs(x)+abs(x+2)-5
How can I do it?
| 0
| 0
| 0
| 0
| 1
| 0
|
I'm making a game in c++. It is a card game. I have made 13 cards that rotate about a point to arc out to make your hand. I need a way to figure out which card the user clicks on. My cards are basically rectangles rotated about a point that is in the center of the cards. I was thinking of maybe getting the mouse point and rotating it about my central point but i'm not sure how to rotate a point about a point. Thanks.
| 0
| 0
| 0
| 0
| 1
| 0
|
I have a dynamic number of equally proportioned and sized rectangular objects that I want to optimally display on the screen. I can resize the objects but need to maintain proportion.
I know what the screen dimensions are.
How can I calculate the optimal number of rows and columns that I will need to divide the screen in to and what size I will need to scale the objects to?
Thanks,
Jamie.
| 0
| 0
| 0
| 0
| 1
| 0
|
Is there some reason that identical math operations would take significantly longer in one Silverlight app than in another?
For example, I have some code that takes a list of points and transforms them (scales and translates them) and populates another list of points. It's important that I keep the original points intact, hence the second list.
Here's the relevant code (scale is a double and origin is a point):
public Point transformPoint(Point point) {
// scale, then translate the x
point.X = (point.X - origin.X) * scale;
// scale, then translate the y
point.Y = (point.Y - origin.Y) * scale;
// return the point
return point;
}
Here's how I'm doing the loop and timing, in case it's important:
DateTime startTime = DateTime.Now;
foreach (Point point in rawPoints) transformedPoints.Add(transformPoint(point));
Debug.Print("ASPX milliseconds: {0}", (DateTime.Now - startTime).Milliseconds);
On a run of 14356 points (don't ask, it's modeled off a real world number in the desktop app), the breakdown is as follows:
Silverlight app #1: 46 ms
Silverlight app #2: 859 ms
The first app is an otherwise empty app that is doing the loop in the MainPage constructor. The second is doing the loop in a method in another class, and the method is called during an event handler in the GUI thread, I think. But should any of that matter, considering that identical operations are happening within the loop itself?
There maybe something huge I'm missing in how threading works or something, but this discrepancy doesn't make sense to me at all.
| 0
| 0
| 0
| 0
| 1
| 0
|
I am trying to do problem 254 in project euler and arrived at this set of functions and refactor in Haskell:
f n = sum $ map fac (decToList n)
sf n = sum $ decToList (f n)
g i = head [ n | n <- [1..], sf n == i]
sg i = sum $ decToList (g i)
answer = sum [ sg i | i <- [1 .. 150] ]
Where:
f (n) finds the sum of the factorials of each digit in n
sf (n) is the sum of the digits in the result of f (n)
g (i) is the smallest integer solution for sf (i). As there can be many results for sf (i)
sg (i) is the sum of the digits in the result of g (i)
But not long into running the compiled version of this script, it sucked up all my RAM. Is there a better way to implement the function g (i)? If so what can they be and how could I go about it?
EDIT:
Just out of clarity, my functions for:
fac is :
`fac 0 = 1`
`fac n = n * fac (n-1)`
decToList which makes a number into a list:
decToList1 x = reverse $ decToList' x
where
decToList' 0 = []
decToList' y = let (a,b) = quotRem y 10 in [b] ++ decToList' a
Although I did since update them to Yairchu's solution for optimisation sake.
| 0
| 0
| 0
| 0
| 1
| 0
|
As a programmer, I frequently need to be able to know the
how to calculate the number of permutations of a set, usually
for estimation purposes.
There are a lot of different ways specify the allowable
combinations, depending on the problem at hand. For example,
given the set of letters A,B,C,D
Assuming a 4 digit result, how many ways can those letters
be arranged?
What if you can have 1,2,3 or 4 digits, then how many ways?
What if you are only allowed to use each letter at most once?
twice?
What if you must avoid the same letter appearing twice in
a row, but if they are not in a row, then twice is ok?
Etc. I'm sure there are many more.
Does anyone know of a web reference or book that talks about
this subject in terms that a non-mathematician can understand?
Thanks!
| 0
| 0
| 0
| 0
| 1
| 0
|
I'm trying to code a 3d wall like
http://www.flashloaded.com/flashcomponents/3dwall/
The shape I am looking to create is like a bath or arena where it is a curve cornered rectangle with sloping sides.
The image below shows what i'm trying to achieve if viewed from above. I hope that helps.
Can anyone give me some ideas on the maths to create this shape using primitive rectangle shapes.
Thanks,
Josh
| 0
| 0
| 0
| 0
| 1
| 0
|
I have a circle. Inside the circle is a point. I have a vector originating at this point. I'd like to know what point on the circle this vector intersects. Here is a drawing:
http://n4te.com/temp/circle.png http://n4te.com/temp/circle.png
The red dot is the point I am trying to determine.
I know these things: the center of the circle, the origin of the vector, and the direction of the vector.
I know this is basic stuff, but I'm still having trouble. Most of the Googlings bring me to line-circle collision, which is related but not quite the same. Thanks for any help you can provide!
| 0
| 0
| 0
| 0
| 1
| 0
|
I have a N-dimensional vector, X and 'n' equidistant points along each dimension and a parameter 'delta'. I need a way to find the total of n^N vectors enclosed by the Hypercube defined with the vector X at the center and each side of Hypercube being of size 2*delta.
For example:
Consider a case of N=3, so we have a Cube of size (2*delta) enclosing the point X.
------------\
|\--------|--\
| | X | |
----------- |
\ |_2*del___\|
Along each dimension I have 'n' points. So, I have a total of n^3 vectors around X. I need to find all the vectors. Is there any standard algorithm/method for the same? If you have done anything similar, please suggest.
If the problem is not clear, let me know.
This is what I was looking at: Considering one dimension, length of a side is 2*delta and I have n divisions. So, each sub-division is of size (2*delta/n). So I just move to the origin that is (x-delta) (since x is the mid point of the side) and obtain the 'n' points by {(x-delta) + 1*(2*delta/n),(x-delta) + 2*(2*delta/n)....+ (x-delta) + 1*(n*delta/n) } . I do this for all the N-dimensions and then take a permutation of the co-ordinates. That way I have all the points.
(I would like to close this)
| 0
| 0
| 0
| 0
| 1
| 0
|
I need to be able to generate a single random number and then use that number to seed a theoretically infinitely large 2d plane on the fly with boolean values. I need a function I can call that is deterministic with three inputs (x, y, and the random seed) and returns a pseudo-random result back:
int r = random()
//...
var value_for_point = f(x,y,r);
If I were to use this function to fill a 10x10 array with ones and zeros, it would ideally look the same as/similar to if I had asked for a random value for each cell as I went along, i.e. white noise. It doesn't have to be perfect - its not for statistical analysis. I just need to be able to recreate the array given the same random number.
I can't simply seed the random number generator for two reasons. First, I need this function to be based on x and y. I may call this function to fill the array between (0,0) and (10, 10), then later ask for the values between (-10,-5) and (3,4). Second, the language I'm using doesn't have a seed function.
I'm sure there's either a trivial way to do this that I'm not seeing or there's something int he domain of fractals that might help me. Anyone know how to do this?
| 0
| 0
| 0
| 0
| 1
| 0
|
First of all: This is not a question about how to make a program play Five in a Row. Been there, done that.
Introductory explanation
I have made a five-in-a-row-game as a framework to experiment with genetically improving AI (ouch, that sounds awfully pretentious). As with most turn-based games the best move is decided by assigning a score to every possible move, and then playing the move with the highest score. The function for assigning a score to a move (a square) goes something like this:
If the square already has a token, the score is 0 since it would be illegal to place a new token in the square.
Each square can be a part of up to 20 different winning rows (5 horizontal, 5 vertical, 10 diagonal). The score of the square is the sum of the score of each of these rows.
The score of a row depends on the number of friendly and enemy tokens already in the row. Examples:
A row with four friendly tokens should have infinite score, because if you place a token there you win the game.
The score for a row with four enemy tokens should be very high, since if you don't put a token there, the opponent will win on his next turn.
A row with both friendly and enemy tokens will score 0, since this row can never be part of a winning row.
Given this algorithm, I have declared a type called TBrain:
type
TBrain = array[cFriendly..cEnemy , 0..4] of integer;
The values in the array indicates the score of a row with either N friendly tokens and 0 enemy tokens, or 0 friendly tokens and N enemy tokens. If there are 5 tokens in a row there's no score since the row is full.
It's actually quite easy to decide which values should be in the array. Brain[0,4] (four friendly tokens) should be "infinite", let's call that 1.000.000. vBrain[1,4] should be very high, but not so high that the brain would prefer blocking several enemy wins rather than wining itself
Concider the following (improbable) board:
0123456789
+----------
0|1...1...12
1|.1..1..1.2
2|..1.1.1..2
3|...111...2
4|1111.1111.
5|...111....
6|..1.1.1...
7|.1..1..1..
8|1...1...1.
Player 2 should place his token in (9,4), winning the game, not in (4,4) even though he would then block 8 potential winning rows for player 1. Ergo, vBrain[1,4] should be (vBrain[0,4]/8)-1. Working like this we can find optimal values for the "brain", but again, this is not what I'm interested in. I want an algorithm to find the best values.
I have implemented this framework so that it's totally deterministic. There's no random values added to the scores, and if several squares have the same score the top-left will be chosen.
Actual problem
That's it for the introduction, now to the interesting part (for me, at least)
I have two "brains", vBrain1 and vBrain2. How should I iteratively make these better? I Imagine something like this:
Initialize vBrain1 and vBrain2 with random values.
Simulate a game between them.
Assign the values from the winner to the loser, then randomly change one of them slightly.
This doesn't seem work. The brains don't get any smarter. Why?
Should the score-method add some small random values to the result, so that two games between the same two brains would be different? How much should the values change for each iteration? How should the "brains" be initialized? With constant values? With random values?
Also, does this have anything to do with AI or genetic algorithms at all?
PS: The question has nothing to do with Five in a Row. That's just something I chose because I can declare a very simple "Brain" to experiment on.
| 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.