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 thought some time about writing a program that tells me if three circles with given diameters can fit inside a triangle with given side lengths without overlapping (touching is ok) each other.
How would one think about doing that?
| 0
| 0
| 0
| 0
| 1
| 0
|
I'm currently working on a keyphrase extraction tool, which should provide tag suggestions for texts or documents on a website. As I am following the method proposed in this paper: A New Approach to Keyphrase Extraction Using Neural Networks I am using the OpenNLP toolkit's POSTagger for the first step, i.e. candidate selection.
In general the keyphrase extraction works pretty well. My problem is that I have to perform this expensive loading of the models from their corresponding files every time I want to use the POSTagger:
posTagger = new POSTaggerME(new POSModel(new FileInputStream(new File(modelDir + "/en-pos-maxent.bin"))));
tokenizer = new TokenizerME(new TokenizerModel(new FileInputStream(new File(modelDir + "/en-token.bin"))));
// ...
String[] tokens = tokenizer.tokenize(text);
String[] tags = posTagger.tag(tokens);
This is due to the fact that this code is not on the scope of the webserver itself but inside a "handler" with a lifecycle including only handling one specific request. My question is: How can I achieve loading the files only once? (I don't want to spend 10 seconds on waiting for the models to load and using it just for 200ms afterwards.)
My first idea was to serialize the POSTaggerME (TokenizerME resp.) and deserialize it every time I need it using Java's built-in mechanism. Unfortunately this doesn't work – it raises an exception. (I do serialize the classifier from the WEKA-toolkit which classifies my candidates at the end in order to not having to build (or train) the classifier every time. Therefore I thougth this may be applicable to the POSTaggeME as well. Unfortunately this is not the case.)
In the case of the Tokenizer I could refer to a simple WhitespaceTokenizer which is an inferior solution but not that bad at all:
tokenizer = WhitespaceTokenizer.INSTANCE;
But I don't see this option for a reliable POSTagger.
| 0
| 1
| 0
| 0
| 0
| 0
|
I wonder what are the advantages and disadvantages of these two algorithms. I want to write AddEmUp C++ solved, but I'm not sure which (IDA or DFID) algorithm should I use.
The best article I found is this one, but it seems too old - '93. Any newer?
I think IDA* would be better, but.. ? Any other ideas?
Any ideas and info would be helpful.
Thanks ! (:
EDIT: Some good article about IDA* and good explanation of the algorithm?
EDIT2: Or some good heuristic function for that game? I have no idea how to think of some :/
| 0
| 1
| 0
| 0
| 0
| 0
|
Suppose we have a set of doubles s, something like this:
1.11, 1.60, 5.30, 4.10, 4.05, 4.90, 4.89
We now want to find the smallest, positive integer scale factor x that any element of s multiplied by x is within one tenth of a whole number.
Sorry if this isn't very clear—please ask for clarification if needed.
Please limit answers to C-style languages or algorithmic pseudo-code.
Thanks!
| 0
| 0
| 0
| 0
| 1
| 0
|
SOLUTION AT BOTTOM OF THIS QUESTION
I have this code:
public void lineImproved(int x0, int y0, int x1, int y1, Color color)
{
int pix = color.getRGB();
int dx = x1 - x0;
int dy = y1 - y0;
raster.setPixel(pix, x0, y0);
if (Math.abs(dx) > Math.abs(dy)) { // slope < 1
float m = (float) dy / (float) dx; // compute slope
float b = y0 - m*x0;
dx = (dx < 0) ? -1 : 1;
while (x0 != x1) {
x0 += dx;
raster.setPixel(pix, x0, Math.round(m*x0 + b));
}
} else
if (dy != 0) { // slope >= 1
float m = (float) dx / (float) dy; // compute slope
float b = x0 - m*y0;
dy = (dy < 0) ? -1 : 1;
while (y0 != y1) {
y0 += dy;
raster.setPixel(pix, Math.round(m*y0 + b), y0);
}
}
}
It currently plots a line and fills in the specific pixels that make up the line between the 2 points specified (i.e. [x0,y0] and [x1,y1]). I need it to include an h0 and h1 for the height of the 2 points. By doing so I hope to be able to obtain a height value on the vertical axis with every raster.setPixel function.
UPDATE
I have now the code how it should be for this task, but still only in 2D. I need to implement the suggested solution to the following code to verify it:
internal static int DrawLine(Player theplayer, Byte drawBlock, int x0, int y0, int z0, int x1, int y1, int z1)
{
int blocks = 0;
bool cannotUndo = false;
int dx = x1 - x0;
int dy = y1 - y0;
int dz = z1 - z0;
DrawOneBlock (theplayer, drawBlock, x0, y0, z0, ref blocks, ref cannotUndo);
if (Math.Abs(dx) > Math.Abs(dy))
{ // slope < 1
float m = (float)dy / (float)dx; // compute slope
float b = y0 - m * x0;
dx = (dx < 0) ? -1 : 1;
while (x0 != x1)
{
x0 += dx;
DrawOneBlock(theplayer, drawBlock, x0, Convert.ToInt32(Math.Round(m * x0 + b)), z0, ref blocks, ref cannotUndo);
}
}
else
{
if (dy != 0)
{ // slope >= 1
float m = (float)dx / (float)dy; // compute slope
float b = x0 - m * y0;
dy = (dy < 0) ? -1 : 1;
while (y0 != y1)
{
y0 += dy;
DrawOneBlock(theplayer, drawBlock, Convert.ToInt32(Math.Round(m * y0 + b)), y0, z0, ref blocks, ref cannotUndo);
}
}
}
return blocks;
}
SOLUTION:
internal static int DrawLine(Player theplayer, Byte drawBlock, int x0, int y0, int z0, int x1, int y1, int z1)
{
int blocks = 0;
bool cannotUndo = false;
bool detected = false;
int dx = x1 - x0;
int dy = y1 - y0;
int dz = z1 - z0;
DrawOneBlock (theplayer, drawBlock, x0, y0, z0, ref blocks, ref cannotUndo);
//a>x,b>y,c>z
if (Math.Abs(dx) > Math.Abs(dy) && Math.Abs(dx) > Math.Abs(dz) && detected == false)
{ // x distance is largest
detected = true;
float my = (float)dy / (float)dx; // compute y slope
float mz = (float)dz / (float)dx; // compute z slope
float by = y0 - my * x0;
float bz = z0 - mz * x0;
dx = (dx < 0) ? -1 : 1;
while (x0 != x1)
{
x0 += dx;
DrawOneBlock(theplayer, drawBlock, Convert.ToInt32(x0), Convert.ToInt32(Math.Round(my * x0 + by)), Convert.ToInt32(Math.Round(mz * x0 + bz)), ref blocks, ref cannotUndo);
}
}
//a>y,b>z,c>x
if (Math.Abs(dy) > Math.Abs(dz) && Math.Abs(dy) > Math.Abs(dx) && detected == false && detected == false)
{ // y distance is largest
detected = true;
float mz = (float)dz / (float)dy; // compute z slope
float mx = (float)dx / (float)dy; // compute x slope
float bz = z0 - mz * y0;
float bx = x0 - mx * y0;
dy = (dy < 0) ? -1 : 1;
while (y0 != y1)
{
y0 += dy;
DrawOneBlock(theplayer, drawBlock, Convert.ToInt32(Math.Round(mx * y0 + bx)), Convert.ToInt32(y0) , Convert.ToInt32(Math.Round(mz * y0 + bz)), ref blocks, ref cannotUndo);
}
}
//a>z,b>x,c>y
if (Math.Abs(dz) > Math.Abs(dx) && Math.Abs(dz) > Math.Abs(dy) && detected == false && detected == false)
{ // z distance is largest
detected = true;
float mx = (float)dx / (float)dz; // compute x slope
float my = (float)dy / (float)dz; // compute y slope
float bx = x0 - mx * z0;
float by = y0 - my * z0;
dz = (dz < 0) ? -1 : 1;
while (z0 != z1)
{
z0 += dz;
DrawOneBlock(theplayer, drawBlock, Convert.ToInt32(Math.Round(mx * z0 + bx)), Convert.ToInt32(Math.Round(my * z0 + by)), Convert.ToInt32(z0), ref blocks, ref cannotUndo);
}
}
| 0
| 0
| 0
| 0
| 1
| 0
|
Up to what string length is it possible to use MD5 as a hash without having to worry about the possibility of a collision?
This would presumably be calculated by generating an MD5 hash for every possible string in a particular character set, in increasing length, until a hash appears for a second time (a collision). The maximum possible length of a string without a collision would then be one character less than the longest of the colliding pair.
Has this already been tested for MD5, SHA1, etc?
| 0
| 0
| 0
| 0
| 1
| 0
|
I hate decimal numbers. For 1.005 I don't get the result I expect with the following code.
#!/usr/bin/perl -w
use strict;
use POSIX qw(floor);
my $num = (1.005 * 100) + 0.5;
print $num . "
"; # 101
print floor($num) . "
"; # 100
print int($num) . "
"; # 100
For 2.005 and 3.005 it works fine.
With this ugly "hack" I get the expected result.
#!/usr/bin/perl -w
use strict;
use POSIX qw(floor);
my $num = (1.005 * 100) + 0.5;
$num = "$num";
print $num . "
"; # 101
print floor($num) . "
"; # 101
print int($num) . "
"; # 101
What is the correct way to do this?
| 0
| 0
| 0
| 0
| 1
| 0
|
I feel like this is a very noob question.. but I just can't get the right statement for it.
For display purposes, I want to split a double in two: the part before the dot and the first two digits after the dot. I need it as a string. Target language: C#.
E.g.: 2345.1234 becomes "2345" and "12"
I know how to get the part before the dot, that's simply:
Math.Floor(value).ToString()
...but what is the right way to get the part "behind the dot"?
There must be some nice way to do that in a simple way...
I can't think of anything else then:
Math.Round(100 * (value - Math.Floor(value))).ToString("00");
I'm sure there is a better way, but I just can't think of it. Anyone?
| 0
| 0
| 0
| 0
| 1
| 0
|
I have an object w/ and orientation and the rotational rates about each of the body axis. I need to find a smooth transition from this state to a second state with a different set of rates. Additionally, I have constraints on how fast I can rotate/accelerate about each of the axis.
I have explored Quaternion slerp's, and while I can use them to smoothly interpolate between the states, I don't see an easy way to get the rate matching into it.
This feels like an exercise in differential equations and path planning, but I'm not sure exactly how to formulate the problem so that the algorithms that are out there can work on it.
Any suggestions for algorithms that can help solve this and/or tips on formulating the problem to work with those algorithms would be greatly appreciated.
[Edit - here is an example of the type of problem I'm working on]
Think of a gunner on a helicopter that needs to track a target as the helicopter is flying. For the sake of argument, he needs to be on the target from the time it rises over the horizon to the time it is no longer in view. The relative rate of this target is not constant, but I assume that through the aggregation of several 'rate matching' maneuvers I can approximate this tracking fairly well. I can calculate the gun orientation and tracking rates required at any point, it's just generating a profile from some discrete orientations and rates that is stumping me.
Thanks!
| 0
| 0
| 0
| 0
| 1
| 0
|
I'm working in Ogre, but it's a general quaternion problem.
I have an object, to which I apply a rotation quaternion Q1 initially. Later, I want to make it as if I initially rotated the object by a different quaternion Q2.
How do I calculate the quaternion which will take the object, already rotated by Q1, and align it as if all I did was apply Q2 to the initial/default orientation? I was looking at (s)lerping, but I am not sure if this only valid on orientations rather than rotations?
| 0
| 0
| 0
| 0
| 1
| 0
|
how to convert Quaternion orientation output of wintracker II device to Euler Angles output only. Because Wintracker II device Output Euler angles and Quaternion orientation. i want to Euler angles output only.
| 0
| 0
| 0
| 0
| 1
| 0
|
Hey. My maths isn't great so I'm hoping someone can help me with this. I have a 1D array of pixels (representing a 2d image). In order to access a specific pixel, I'm using this formula:
image.Pixels[row * imageWidth + col] = pixelColor;
This is working, but I would also like to include pixels around the selected pixel. What's the fastest way, without using pointers directly, to get a group of pixels around the selected pixel with a radius of r and set their values to pixelColor? I'm trying to create a paint-type app and would like to vary brush sizes, which would be dictated by the radius size.
Thanks for any help.
| 0
| 0
| 0
| 0
| 1
| 0
|
Here is the code.
function product_analysis_global() {
$(':checkbox:checked').each(function() {
$('#product_' + this.alt).load(this.title);
$('#product_quantity_PRI_' + this.alt).value = this.value;
});
}
All working except the last line that is not working, any ideas. Should return the value of the current checkbox to the appropriate field '#product_quantity_PRI_' + this.alt
Many Thanks.
| 0
| 0
| 0
| 0
| 1
| 0
|
If I enter the a location of:
Latitude = 28 Degrees, 45 Minutes, 12 Seconds
Longitude = 81 Degrees, 39 Minutes, 32.4 Seconds
It gets converted into Decimal Degrees format to be stored in the database with the following code:
Coordinates coordinates = new Coordinates();
coordinates.LatitudeDirection = this.radLatNorth.Checked ? Coordinates.Direction.North : Coordinates.Direction.South;
coordinates.LatitudeDegree = this.ConvertDouble(this.txtLatDegree.Text);
coordinates.LatitudeMinute = this.ConvertDouble(this.txtLatMinute.Text);
coordinates.LatitudeSecond = this.ConvertDouble(this.txtLatSecond.Text);
coordinates.LongitudeDirection = radLongEast.Checked ? Coordinates.Direction.East : Coordinates.Direction.West;
coordinates.LongitudeDegree = this.ConvertDouble(this.txtLongDegree.Text);
coordinates.LongitudeMinute = this.ConvertDouble(this.txtLongMinute.Text);
coordinates.LongitudeSecond = this.ConvertDouble(this.txtLongSecond.Text);
//gets the calulated fields of Lat and Long
coordinates.ConvertDegreesMinutesSeconds();
In the above code, ConvertDouble is defined as:
private double ConvertDouble(string value)
{
double newValue = 0;
double.TryParse(value, out newValue);
return newValue;
}
and ConvertDegreesMinutesSeconds is defined as:
public void ConvertDegreesMinutesSeconds()
{
this.Latitude = this.LatitudeDegree + (this.LatitudeMinute / 60) + (this.LatitudeSecond / 3600);
this.Longitude = this.LongitudeDegree + (this.LongitudeMinute / 60) + (this.LongitudeSecond / 3600);
//adds the negative sign
if (LatitudeDirection == Direction.South)
{
this.Latitude = 0 - this.Latitude;
}
else if (LongitudeDirection == Direction.West)
{
this.Longitude = 0 - this.Longitude;
}
}
If I don't make any change to the latitude or longitude and I click Apply Changes which basically does the above calucation again, it generates a different latitude and longitude in the database. This happens every time I go to edit it and don't make a change (I just click Apply Changes and it does the calculation again with a different result).
In the above scenario, the new Latitude and Longitude is:
Latitude = 28 Degrees, 45 Minutes, 12 Seconds
Longitude = 81 Degrees, 40 Minutes, 32.4 Seconds
If I do it again, it becomes:
Latitude = 28 Degrees, 45 Minutes, 12 Seconds
Longitude = 81 Degrees, 41 Minutes, 32.4 Seconds
The other part of this is that when I go into edit, it takes the decimal degrees format of the latitude and longitude and converts it to the degrees minutes seconds format and puts them into their respective textboxes. The code for that is:
public void SetFields()
{
Coordinates coordinateLocation = new Coordinates();
coordinateLocation.Latitude = this.Latitude;
coordinateLocation.Longitude = this.Longitude;
coordinateLocation.ConvertDecimal();
this.radLatNorth.Checked =
coordinateLocation.LatitudeDirection == Coordinates.Direction.North;
this.radLatSouth.Checked = !this.radLatNorth.Checked;
this.txtLatDegree.Text = coordinateLocation.LatitudeDegree.ToString().Replace("-", string.Empty);
this.txtLatMinute.Text = Math.Round(coordinateLocation.LatitudeMinute, 0).ToString().Replace("-", string.Empty);
this.txtLatSecond.Text = Math.Round(coordinateLocation.LatitudeSecond, 2).ToString().Replace("-", string.Empty);
this.radLongEast.Checked =
coordinateLocation.LongitudeDirection == Coordinates.Direction.East;
this.radLongWest.Checked = !this.radLongEast.Checked;
this.txtLongDegree.Text = coordinateLocation.LongitudeDegree.ToString().Replace("-", string.Empty); ;
this.txtLongMinute.Text = Math.Round(coordinateLocation.LongitudeMinute, 0).ToString().Replace("-", string.Empty);
this.txtLongSecond.Text = Math.Round(coordinateLocation.LongitudeSecond, 2).ToString().Replace("-", string.Empty);
}
From the above examples, you can see that the Minute kept increasing by 1, which would indicate why it is generating a different latitude and longitude in decimal degrees in the database, so I guess the problem is more in the above area, but I am not sure where or why it is doing it?
public void ConvertDecimal()
{
this.LatitudeDirection = this.Latitude > 0 ? Direction.North : Direction.South;
this.LatitudeDegree = (int)Math.Truncate(this.Latitude);
if (LatitudeDirection == Direction.South)
{
this.LatitudeDegree = 0 - this.LatitudeDegree;
}
this.LatitudeMinute = (this.Latitude - Math.Truncate(this.Latitude)) * 60;
this.LatitudeSecond = (this.LatitudeMinute - Math.Truncate(this.LatitudeMinute)) * 60;
this.LongitudeDirection = this.Longitude > 0 ? Direction.East : Direction.West;
this.LongitudeDegree = (int)Math.Truncate(this.Longitude);
if (LongitudeDirection == Direction.West)
{
this.LongitudeDegree = 0 - this.LongitudeDegree;
}
this.LongitudeMinute = (this.Longitude - Math.Truncate(this.Longitude)) * 60;
this.LongitudeSecond = (this.LongitudeMinute - Math.Truncate(this.LongitudeMinute)) * 60;
}
| 0
| 0
| 0
| 0
| 1
| 0
|
I process different binary data. Mostly, these are signed 16-bit streams. With hexdump, it looks like:
...
2150 -191 -262 15 -344 -883 -820 -1038 -780
-1234 -1406 -693 131 433 396 241 600 1280
...
I would like to see only those elements of a data stream, which are greater than or less than some threshold (data is binary signed 16-bit). It could look like:
cat data.pcm | $($here_some_filtering) 2100 -2100
where output must give me only elements which are greater than 2100 and less than -2100. Is there any simple command-line method how to do it?
| 0
| 0
| 0
| 0
| 1
| 0
|
I'd like to do a hypot2 calculation on a 16-bit processor.
The standard formula is c = sqrt((a * a) + (b * b)). The problem with this is with large inputs it overflows. E.g. 200 and 250, multiply 200 * 200 to get 90,000 which is higher than the max signed value of 32,767, so it overflows, as does b, the numbers are added and the result may as well be useless; it might even signal an error condition because of a negative sqrt.
In my case, I'm dealing with 32-bit numbers, but 32-bit multiply on my processor is very fast, about 4 cycles. I'm using a dsPIC microcontroller. I'd rather not have to multiply with 64-bit numbers because that's wasting precious memory and undoubtedly will be slower. Additionally I only have sqrt for 32-bit numbers, so 64-bit numbers would require another function. So how can I compute a hypot when the values may be large?
Please note I can only really use integer math for this. Using anything like floating point math incurs a speed hit which I'd rather avoid. My processor has a fast integer/fixed point atan2 routine, about 130 cycles; could I use this to compute the hypotenuse length?
| 0
| 0
| 0
| 0
| 1
| 0
|
I have some troubles understanding some of the algorithms for searching, used in AI (artificial intelligence).
What is the exact difference between A* and IDA* (Iterative Deeping A Star)? Is just the heuristic function? If so, I still just can't imagine how IDA* works.. :/
Is IDA* the same as BFS (Breadth-First search) (when the depth of expanding is just 1 level, I mean - moving just one by one level "down", is there any difference between IDA* and BFS)
Is IDDFS (Iterative-Deeping Depth-First Search) the same as IDA*, except the heuristic function (which is equivalent to 0 in IDDFS)
What exactly is IDDFS - moving down just one level, then using DFS (Depth-First Search)? If so, this way lots of the states are calculated (expanded) much more than ones.. Or it's like this - use DFS with particular depth, then store the "leaves" (the last expanded nodes), and iterate through them to use DFS again (which, actually, is BFS?)
Where "iterative" comes from? As I see, IDDFS is not iterative at all, it's still recursiive, just mixes BFS and DFS? Or I'm wrong? Or this "iterative" has nothing to do with the opposite of recursion?
What is "iterative" for IDA* ?
Could you, please, provide some examples? I read all day about these algorithms, I know their advantages and disadvantages, the complexity, etc., but I just couldn't find any good examples (except for A*; I know BFS and DFS, the others bother me). I found some pseudo-code for IDA* on different places, but they were all completely different.
Examples would be the best way to understand algorithms..but I can't find. Even in TopCoder I didn't find anything about IDA*.
I've read the wiki articles and I'm looking for something new (:
Thanks a lot!
EDIT: Here some nice articles, but they are too theoretical. No examples, no any specific things. But still very useful. I'd recommend them (=
| 0
| 1
| 0
| 0
| 0
| 0
|
lets say i have an expression:
(n)+((n-1)*2)+((n-2)*3)+((n-3)*4)+...+(3*(n-2))+(2*(n-1))+(1*(n))
what is the tight bound of this? or the upper bound? is this n^3? is this n^4? the maximum amount of number i can get out of this? thanks
EDIT: so: for i=1 then: the ans is 1.
i=2: (1*2 + 2*1)
1=3: (1*3 + 2*2 + 3*1)
i=4: (1*4 + 2*3 + 3*2 + 4*1 )
and so on
| 0
| 0
| 0
| 0
| 1
| 0
|
I have in my android application a database table with geo pointes (lat and lon are decimal degree values), about 1000 points. And I need to select 20 nearest point to some given geo point.
I've found at Stackoverflow the answer how to compute distance between two geo points and was very happy, till I tried to write my query. I've found out, that it's not possible to use trignometrical functions in built-in sqlite of android.
But then I've got an Idea. I don't really need to compute a distance. The near a point is to another one the smaller difference in their geo coordinates should be.
How could I use this fact? Would it be enough to order saved points by (lat_0 - lat_n)^2 + (lon0-lon_n)^2, where lat_0 and lon_0 are geo coordinates of a given point?
Thank you,
Mur
UPD
So, the best way to get an answer for my question was to test approach I describe above.
It works pretty well but not really exactly compared to exact distance.
So if you just need to compute a distance, this solution is ok, but in my case I also needed to order stations by distance and couldn't use this solution.
My thanks go on John at CashCommons and Philip. Thank you guys
| 0
| 0
| 0
| 0
| 1
| 0
|
I am having two Vectors (X,Y,Z), one above Y=0 and one below Y=0.
I want to find the Vector (X,Y,Z) where the line between the two original vectors intersects with the Y=0 level.
How do I do that?
Example Point A:
X = -43.54235
Y = 95.2679138
Z = -98.2120361
Example Point B:
X = -43.54235
Y = 97.23531
Z = -96.24464
These points read from two UnProjections from a users click and I'm trying to target the unprojection to Y=0.
(I found 3D line plane intersection, with simple plane but didn't understand the accepted answer as it's for 2D)
| 0
| 0
| 0
| 0
| 1
| 0
|
Sum[(i + 1) (n - i), {i, 0, n - 1}]
that is a sum of ( i+1)(n-1) with bounds from i=0 to n-1.
is that O(n^2) or O(n^3)?
and can you explain me how you found it? thanks.
| 0
| 0
| 0
| 0
| 1
| 0
|
Possible Duplicate:
Solving a linear equation
I need to programmatically solve a system of linear equations in C# AND VB
Here's an example of the equations:
12.40 = a * 56.0 + b * 27.0 + tx
-53.39 = a * 12.0 + b * 59.0 + tx
14.94 = a * 53.0 + b * 41.0 + tx
I'd like to get the best approximation for a, b, and tx.
Should i use some sort of matrix class or something?
| 0
| 0
| 0
| 0
| 1
| 0
|
Having a rectangle (A) and intersecting it with another rectangle (B), how could I extract the other rectangles created through that intersection (C,D,E & F)?
AAAAAAAAAAAAAA CCCFFFFDDDDDDD
AAABBBBAAAAAAA CCCBBBBDDDDDDD
AAABBBBAAAAAAA -> CCCBBBBDDDDDDD
AAAAAAAAAAAAAA CCCEEEEDDDDDDD
AAAAAAAAAAAAAA CCCEEEEDDDDDDD
And could this be extended to extract rectangles from several intersections, such as this example which intersects A with B & C and extracts D, E, F & G?
BBBBAAAAAAAAAA BBBBDDDDDDDDDD
BBBBAAAAAAAAAA BBBBDDDDDDDDDD
AAAAAACCCCCAAA -> EEEEEECCCCCFFF
AAAAAACCCCCAAA EEEEEECCCCCFFF
AAAAAAAAAAAAAA EEEEEEGGGGGFFF
| 0
| 0
| 0
| 0
| 1
| 0
|
I'm having problems converting between local and global coordinates while projecting a rectangle onto different axes using the separated axis theorem: http://en.wikipedia.org/wiki/Separating_axis_theorem. In the end, I'd like to check for collision with another object.
Let's say I have a rectangle with vertices in global coordinates of:
(10,20),(10,10),(20,10),(20,20)
The local coordinates would thus be:
(-5,5),(-5,-5),(5,-5),(5,5)
This would make the 4 normals the following: (1 for each axis)
(1,0),(0,1),(-1,0),(0,-1)
The min/max dot products for the would then be:
(1,0) . (-5,5) = -5
(1,0) . (-5,-5) = -5
(1,0) . (5,-5) = 5
(1,0) . (5,5) = 5
So the min/max pair for this normal is (-5,5), as are all the others in this case due to symmetry.
The problem comes when I want to convert the coordinates back into global coordinates. From my understanding, I need to shift the min/max pairs by the projection of the given axis onto it's global position.
This works fine when using the positive unit vectors:
unit center of rect
(1,0) . (15, 15) = 15
This means that the adjusted min/max values would be 15-5,15+5 = 10,20 which is correct
However, when I do this for the negative unit vectors, I get:
(-1,0) . (15, 15) = -15, meaning that the min,max values are now (-20,-10)
I don't think this is correct? Is this how the algorithm is supposed to work?
Note: I'm trying to make the code work for all convex polygons, so I can't simply ignore the negative unit vectors for this rectangle.
| 0
| 0
| 0
| 0
| 1
| 0
|
These are some sample algebraic equations
2x = 3
3x + 5 = 8
(y+1)/7 = (y-2)/3
Is there a java API which you can use to create such equations using a java program and return an equivalent HTML which in turn can be used for rendering purposes.
| 0
| 0
| 0
| 0
| 1
| 0
|
i am working on an implementation of the Separting Axis Theorem for use in 2D games. It kind of works but just kind of.
I use it like this:
bool penetration = sat(c1, c2) && sat(c2, c1);
Where c1 and c2 are of type Convex, defined as:
class Convex
{
public:
float tx, ty;
public:
std::vector<Point> p;
void translate(float x, float y) {
tx = x;
ty = y;
}
};
(Point is a structure of float x, float y)
The points are typed in clockwise.
My current code (ignore Qt debug):
bool sat(Convex c1, Convex c2, QPainter *debug)
{
//Debug
QColor col[] = {QColor(255, 0, 0), QColor(0, 255, 0), QColor(0, 0, 255), QColor(0, 0, 0)};
bool ret = true;
int c1_faces = c1.p.size();
int c2_faces = c2.p.size();
//For every face in c1
for(int i = 0; i < c1_faces; i++)
{
//Grab a face (face x, face y)
float fx = c1.p[i].x - c1.p[(i + 1) % c1_faces].x;
float fy = c1.p[i].y - c1.p[(i + 1) % c1_faces].y;
//Create a perpendicular axis to project on (axis x, axis y)
float ax = -fy, ay = fx;
//Normalize the axis
float len_v = sqrt(ax * ax + ay * ay);
ax /= len_v;
ay /= len_v;
//Debug graphics (ignore)
debug->setPen(col[i]);
//Draw the face
debug->drawLine(QLineF(c1.tx + c1.p[i].x, c1.ty + c1.p[i].y, c1.p[(i + 1) % c1_faces].x + c1.tx, c1.p[(i + 1) % c1_faces].y + c1.ty));
//Draw the axis
debug->save();
debug->translate(c1.p[i].x, c1.p[i].y);
debug->drawLine(QLineF(c1.tx, c1.ty, ax * 100 + c1.tx, ay * 100 + c1.ty));
debug->drawEllipse(QPointF(ax * 100 + c1.tx, ay * 100 + c1.ty), 10, 10);
debug->restore();
//Carve out the min and max values
float c1_min = FLT_MAX, c1_max = FLT_MIN;
float c2_min = FLT_MAX, c2_max = FLT_MIN;
//Project every point in c1 on the axis and store min and max
for(int j = 0; j < c1_faces; j++)
{
float c1_proj = (ax * (c1.p[j].x + c1.tx) + ay * (c1.p[j].y + c1.ty)) / (ax * ax + ay * ay);
c1_min = min(c1_proj, c1_min);
c1_max = max(c1_proj, c1_max);
}
//Project every point in c2 on the axis and store min and max
for(int j = 0; j < c2_faces; j++)
{
float c2_proj = (ax * (c2.p[j].x + c2.tx) + ay * (c2.p[j].y + c2.ty)) / (ax * ax + ay * ay);
c2_min = min(c2_proj, c2_min);
c2_max = max(c2_proj, c2_max);
}
//Return if the projections do not overlap
if(!(c1_max >= c2_min && c1_min <= c2_max))
ret = false; //return false;
}
return ret; //return true;
}
What am i doing wrong? It registers collision perfectly but is over sensitive on one edge (in my test using a triangle and a diamond):
//Triangle
push_back(Point(0, -150));
push_back(Point(0, 50));
push_back(Point(-100, 100));
//Diamond
push_back(Point(0, -100));
push_back(Point(100, 0));
push_back(Point(0, 100));
push_back(Point(-100, 0));
I am getting this mega-adhd over this, please help me out :)
http://u8999827.fsdata.se/sat.png
| 0
| 0
| 0
| 0
| 1
| 0
|
Google Calculator formats math expressions this way:
2+2/2 ---> 2 + (2 / 2)
2+2/2*PI ---> 2 + ((2 / 2) * PI)
In others words - it adds brackets.
Are there any similar PHP or JavaScript solutions to do the same thing?
| 0
| 0
| 0
| 0
| 1
| 0
|
Is it possible to implement artificial intelligence concept in jquery?
| 0
| 1
| 0
| 0
| 0
| 0
|
I'm trying to multiply and input amount by 3.5%, Can anyone give me any ideas how to do it?
$("#invest_amount").keyup(function() {
$('#fee').val($('#invest_amount').val() + 3.5);
});
| 0
| 0
| 0
| 0
| 1
| 0
|
I have a simple question.
I have two values MIN and MAX. Then i have a series of values (X) that can be between 0 and +infinity.
Now I want to have an algorithm that maps each value x of X into the range between MIN and MAX.
| 0
| 0
| 0
| 0
| 1
| 0
|
I have a geographical area that has a polygon like shape. I want to scan that area with determined steps, say ~25-30 meters per step. I'm using lat/long system. All I need is a way to do this type of scanning. Efficiency is a plus.
Also, If you can help me find a way to pick points on the border of this polygon with the same steps mentioned above.
Note: I don't care for 100% accurate results.
| 0
| 0
| 0
| 0
| 1
| 0
|
I have just discussed with student and he told me him task, and I think it is interesting.
The task.
There are file with points like:
Point0: x=1; y=4;
Point1: x=199; y=45;
Point2: x=42; y=333;
Point3: x=444; y=444;
...
PointN: x=nnn; y=mmm;
You should find polygons and draw them. Each polygon present as internal
I mean something like this:
---------
| ----- |
| | | |
| |----| |
| |
|--------|
And question what algorithm can you advice to use in this case?
I understand this is from graph theory , but want opinion of other.
Thanks.
| 0
| 0
| 0
| 0
| 1
| 0
|
I am using a base-conversion algorithm to generate a permutation from a large integer (split into 32-bit words).
I use a relatively standard algorithm for this:
/* N = count,K is permutation index (0..N!-1) A[N] contains 0..N-1 */
i = 0;
while (N > 1) {
swap A[i] and A[i+(k%N)]
k = k / N
N = N - 1
i = i + 1
}
Unfortunately, the divide and modulo each iteration adds up, especially moving to large integers - But, it seems I could just use multiply!
/* As before, N is count, K is index, A[N] contains 0..N-1 */
/* Split is arbitrarily 128 (bits), for my current choice of N */
/* "Adjust" is precalculated: (1 << Split)/(N!) */
a = k*Adjust; /* a can be treated as a fixed point fraction */
i = 0;
while (N > 1) {
a = a*N;
index = a >> Split;
a = a & ((1 << Split) - 1); /* actually, just zeroing a register */
swap A[i] and A[i+index]
N = N - 1
i = i + 1
}
This is nicer, but doing large integer multiplies is still sluggish.
Question 1:
Is there a way of doing this faster?
Eg. Since I know that N*(N-1) is less than 2^32, could I pull out those numbers from one word, and merge in the 'leftovers'?
Or, is there a way to modify an arithetic decoder to pull out the indicies one at a time?
Question 2:
For the sake of curiosity - if I use multiplication to convert a number to base 10 without the adjustment, then the result is multiplied by (10^digits/2^shift). Is there a tricky way to remove this factor working with the decimal digits? Even with the adjustment factor, this seems like it would be faster -- why wouldn't standard libraries use this vs divide and mod?
| 0
| 0
| 0
| 0
| 1
| 0
|
How to get digits out of text in JavaScript or jQuery?
Like this one in PHP:
<?php
$a = "2 Apples";
$b = "3 Peach";
echo $a + $b // It will print 5! Thanks for this stupid smartness, 2 apples + 3 peaches should be 2 apples and 3 peaches or maybe a nice jam!
?>
Now I want to do something like this with JavaScript with/without jQuery.
var a = "100$";
var b = "120$";
var ttl = 100 - Math.round( a + b );
Even if I used (a + b * 1) and also (a*1) + (b*1) to see if it turns it to Int, it returned NaN!
| 0
| 0
| 0
| 0
| 1
| 0
|
Lately I worked on a project in Computer Vision that involved implementing lot of linear algebra equations in the code. So I had around 2 sheets of math equations which I implemented.
I have scanned the sheets and I put them along side my project code, and as I am LaTeX'ing them now in a separate PDF, am wondering wouldn't it be nice to have these equations in the code comments just above the function that implements it? (something like the IDE being able to generate beautiful equations in the code comments from the LaTeX code I write, does it sound like a good idea?)
| 0
| 0
| 0
| 0
| 1
| 0
|
I am trying to place currency trades that match an exact rate on a market that only accepts integral bid/offer amounts. I want to make the largest trade possible at a specific rate. This is a toy program, not a real trading bot, so I am using C#.
I need an algorithm that returns an answer in a reasonable amount of time even when the numerator and denominator can be large (100000+).
static bool CalcBiggestRationalFraction(float target_real, float epsilon, int numerator_max, int denominator_max, out int numerator, out int denominator)
{
// target_real is the ratio we are tryig to achieve in our output fraction (numerator / denominator)
// epsilon is the largest difference abs(target_real - (numerator / denominator)) we are willing to tolerate in the answer
// numerator_max, denominator_max are the upper bounds on the numerator and the denominator in the answer
//
// in the case where there are multiple answers, we want to return the largest one
//
// in the case where an answer is found that is within epsilon, we return true and the answer.
// in the case where an answer is not found that is within epsilon, we return false and the closest answer that we have found.
//
// ex: CalcBiggestRationalFraction(.5, .001, 4, 4, num, denom) returns (2/4) instead of (1/2).
}
I asked a previous question that is similar (http://stackoverflow.com/questions/4385580/finding-the-closest-integer-fraction-to-a-given-random-real) before I thought about what I was actually trying to accomplish and it turns out that I am trying to solve a different, but related problem.
| 0
| 0
| 0
| 0
| 1
| 0
|
In R Formula package, it introduces notions for multipart formula like y ~ x1 + x2|I(x1^2).
What's this formula mean mathematically? How's this different from y ~ x1 + x2 + I(x1^2) or two independent y ~ x1 + x2 and y ~ I(x1^2)?
| 0
| 0
| 0
| 0
| 1
| 0
|
I'm sat at my desk and I just thought up a problem and I was wondering if anyone could think up a solution or a way to prove this mathematically.
Say I wanted to find the shortest string of numbers, which contained every number between 0 and 1000. For example, the string "1433" contains the numbers, 1, 4, 3, 14, 43, 33, 143, and 433.
What algorithm could I use to construct the shortest string which contained all numbers 0-1000.
I don't have any practical reason why I want to know, but I'd be interested to hear if there is one.
| 0
| 0
| 0
| 0
| 1
| 0
|
is there any way to access a flash game with a progamming language (.NET prefered)?
I'm interested in AI and love having fun with genetic algorithms. I wondered, if I could write my own AI for some flash games, e.g. http://www.foddy.net/Athletics.html . For this game I simply would need a way to press the buttons and have the game state in some way delivered to my AI.
Is there some general interface or do I have to do it the raw way (analyzing screenshots and sending keystrokes to my browser)?
| 0
| 1
| 0
| 0
| 0
| 0
|
I'm working with a recipe database application and I need the ability to convert natural language strings to numbers and vice versa. For example, I need 1 1/4 to convert to 1.25, and I'll need to be able to convert 1.25 back into 1 1/4.
Is there any library or built-in functions that can do this?
| 0
| 1
| 0
| 0
| 0
| 0
|
Is there a java class abstraction to denote scientific numbers (e.g. the number, 10 power modulus), so that I can do simple operations like multiplication or division on top of them.
Note: Looking for something similar to Fraction here.
| 0
| 0
| 0
| 0
| 1
| 0
|
I'm implementing PCA using eigenvalue decomposition for sparse data. I know matlab has PCA implemented, but it helps me understand all the technicalities when I write code.
I've been following the guidance from here, but I'm getting different results in comparison to built-in function princomp.
Could anybody look at it and point me in the right direction.
Here's the code:
function [mu, Ev, Val ] = pca(data)
% mu - mean image
% Ev - matrix whose columns are the eigenvectors corresponding to the eigen
% values Val
% Val - eigenvalues
if nargin ~= 1
error ('usage: [mu,E,Values] = pca_q1(data)');
end
mu = mean(data)';
nimages = size(data,2);
for i = 1:nimages
data(:,i) = data(:,i)-mu(i);
end
L = data'*data;
[Ev, Vals] = eig(L);
[Ev,Vals] = sort(Ev,Vals);
% computing eigenvector of the real covariance matrix
Ev = data * Ev;
Val = diag(Vals);
Vals = Vals / (nimages - 1);
% normalize Ev to unit length
proper = 0;
for i = 1:nimages
Ev(:,i) = Ev(:,1)/norm(Ev(:,i));
if Vals(i) < 0.00001
Ev(:,i) = zeros(size(Ev,1),1);
else
proper = proper+1;
end;
end;
Ev = Ev(:,1:nimages);
| 0
| 0
| 0
| 1
| 0
| 0
|
I'm working on a project which requires me to calculate the heading from a variable point A to a variable point B in 0 - 360 degrees to let the object at point A face point B.
Now, I'm unsure on how to achieve this, I googled but didn't find any good solution.
How would I calculate the heading from point A to point B in 2D space in any situation?
| 0
| 0
| 0
| 0
| 1
| 0
|
class path_finder ():
def __init__ (self):
# map is a 1-DIMENSIONAL array.
# use the Unfold( (row, col) ) function to convert a 2D coordinate pair
# into a 1D index to use with this array.
self.map = {}
self.size = (-1, -1) # rows by columns
self.pathChainRev = ""
self.pathChain = ""
# starting and ending nodes
self.start = (-1, -1)
self.end = (-1, -1)
# current node (used by algorithm)
self.current = (-1, -1)
# open and closed lists of nodes to consider (used by algorithm)
self.openList = []
self.closedList = []
# used in algorithm (adjacent neighbors path finder is allowed to consider)
#self.neighborSet = [ (0, -1), (0, 1), (-1, 0), (1, 0) ]
#changed to Up Left Down Right
self.neighborSet = [ (0, 1), (-1, 0), (0, -1), (1, 0) ]
def ResizeMap (self, (numRows, numCols)):
self.map = {}
self.size = (numRows, numCols)
# initialize path_finder map to a 2D array of empty nodes
for row in range(0, self.size[0], 1):
for col in range(0, self.size[1], 1):
self.Set( (row, col), node() )
self.SetType( (row, col), 0 )
def CleanUpTemp (self):
# this resets variables needed for a search (but preserves the same map / maze)
self.pathChainRev = ""
self.pathChain = ""
self.current = (-1, -1)
self.openList = []
self.closedList = []
def FindPath (self, startPos, endPos ):
self.CleanUpTemp()
# (row, col) tuples
self.start = startPos
self.end = endPos
# add start node to open list
self.AddToOpenList( self.start )
self.SetG ( self.start, 0 )
self.SetH ( self.start, 0 )
self.SetF ( self.start, 0 )
doContinue = True
while (doContinue == True):
# GNode + HNode = FNode (Anjos)
thisLowestFNode = self.GetLowestFNode()
# If not @end node, and not not lowest cost (Anjos)
# then set lowest f node to current (Anjos)
# Add to ClosedList (current) (Anjos)
if not thisLowestFNode == self.end and not thisLowestFNode == False:
self.current = thisLowestFNode
self.RemoveFromOpenList( self.current )
self.AddToClosedList( self.current )
# an offset within an array or other data structure object is an integer indicating the distance (displacement) (Anjos)
# from the beginning of the object up until a given element or point, presumably within the same object (Anjos)
for offset in self.neighborSet:
thisNeighbor = (self.current[0] + offset[0], self.current[1] + offset[1])
# if 1st and 2nd are smaller than 0, if it's 1st and 2nd size isn't smaller than itself -1, and if it's not a wall (Anjos)
if not thisNeighbor[0] < 0 and not thisNeighbor[1] < 0 and not thisNeighbor[0] > self.size[0] - 1 and not thisNeighbor[1] > self.size[1] - 1 and not self.GetType( thisNeighbor ) == 1:
cost = self.GetG( self.current ) + 10
# then the cost is whatever our current cost was ^+10.^ (Anjos)
if self.IsInOpenList( thisNeighbor ) and cost < self.GetG( thisNeighbor ):
self.RemoveFromOpenList( thisNeighbor )
# if neighbor is in OpenList, and cost is smaller than G of thisNeighbor, remove from OpenList (Path Choice nullified) (Anjos)
#if self.IsInClosedList( thisNeighbor ) and cost < self.GetG( thisNeighbor ):
# self.RemoveFromClosedList( thisNeighbor )
# if NOT thisNeighbor inOpenList and NOT thisNeighbor inClosedList - add thisNeighbor to OpenList (Anjos)
# set G (previous cost)of thisNeighbor to cost (Anjos)
# calculate thisNeighbor's H(Manhattan) and F (Total) (Anjos)
# set thisNeighbor's parent node to current (Anjos)
if not self.IsInOpenList( thisNeighbor ) and not self.IsInClosedList( thisNeighbor ):
self.AddToOpenList( thisNeighbor )
self.SetG( thisNeighbor, cost )
self.CalcH( thisNeighbor )
self.CalcF( thisNeighbor )
self.SetParent( thisNeighbor, self.current )
# else stop (Anjos)
else:
doContinue = False
# If this isn't the lowest path cost then return False (Anjos)
if thisLowestFNode == False:
return False
# Restart Path Logic? (Anjos)
# reconstruct path
self.current = self.end
while not self.current == self.start: # While the current is NOT the start (Anjos)
# build a string representation of the path using R, L, D, U
if self.current[1] > self.GetParent(self.current)[1]: # current[1] > parent(current[1]) (Anjos)
self.pathChainRev += 'R' # add Right (Anjos)
elif self.current[1] < self.GetParent(self.current)[1]: # current[1] < parent(current[1]) (Anjos)
self.pathChainRev += 'L' # add Left (Anjos)
elif self.current[0] > self.GetParent(self.current)[0]: # current[0] > parent(current[0]) (Anjos)
self.pathChainRev += 'D' # add Down (Anjos)
elif self.current[0] < self.GetParent(self.current)[0]: # current[0] < parent(current[0]) (Anjos)
self.pathChainRev += 'U' # add Up (Anjos)
self.current = self.GetParent(self.current) # get parent from current node (Anjos)
self.SetType( self.current, 4) # set current's Type to 4 ?? No clue what 4 is besides the intermitent ghost (Anjos)
# because pathChainRev was constructed in reverse order, it needs to be reversed!
for i in range(len(self.pathChainRev) - 1, -1, -1):
self.pathChain += self.pathChainRev[i]
# set start and ending positions for future reference
self.SetType( self.start, 2)
self.SetType( self.end, 3)
return self.pathChain
def Unfold (self, (row, col)):
# this function converts a 2D array coordinate pair (row, col)
# to a 1D-array index, for the object's 1D map array.
return (row * self.size[1]) + col
def Set (self, (row, col), newNode):
# sets the value of a particular map cell (usually refers to a node object)
self.map[ self.Unfold((row, col)) ] = newNode
def GetType (self, (row, col)):
return self.map[ self.Unfold((row, col)) ].type
def SetType (self, (row, col), newValue):
self.map[ self.Unfold((row, col)) ].type = newValue
def GetF (self, (row, col)):
return self.map[ self.Unfold((row, col)) ].f
def GetG (self, (row, col)):
return self.map[ self.Unfold((row, col)) ].g
def GetH (self, (row, col)):
return self.map[ self.Unfold((row, col)) ].h
def SetG (self, (row, col), newValue ):
self.map[ self.Unfold((row, col)) ].g = newValue
def SetH (self, (row, col), newValue ):
self.map[ self.Unfold((row, col)) ].h = newValue
def SetF (self, (row, col), newValue ):
self.map[ self.Unfold((row, col)) ].f = newValue
def CalcH (self, (row, col)):
self.map[ self.Unfold((row, col)) ].h = abs(row - self.end[0]) + abs(col - self.end[0])
def CalcF (self, (row, col)):
unfoldIndex = self.Unfold((row, col))
self.map[unfoldIndex].f = self.map[unfoldIndex].g + self.map[unfoldIndex].h
def AddToOpenList (self, (row, col) ):
self.openList.append( (row, col) )
def RemoveFromOpenList (self, (row, col) ):
self.openList.remove( (row, col) )
def IsInOpenList (self, (row, col) ):
if self.openList.count( (row, col) ) > 0:
return True
else:
return False
def GetLowestFNode (self):
lowestValue = 1000 # start arbitrarily high
lowestPair = (-1, -1)
for iOrderedPair in self.openList:
if self.GetF( iOrderedPair ) < lowestValue:
lowestValue = self.GetF( iOrderedPair )
lowestPair = iOrderedPair
if not lowestPair == (-1, -1):
return lowestPair
else:
return False
def AddToClosedList (self, (row, col) ):
self.closedList.append( (row, col) )
def IsInClosedList (self, (row, col) ):
if self.closedList.count( (row, col) ) > 0:
return True
else:
return False
def SetParent (self, (row, col), (parentRow, parentCol) ):
self.map[ self.Unfold((row, col)) ].parent = (parentRow, parentCol)
def GetParent (self, (row, col) ):
return self.map[ self.Unfold((row, col)) ].parent
def draw (self):
for row in range(0, self.size[0], 1):
for col in range(0, self.size[1], 1):
thisTile = self.GetType((row, col))
screen.blit (tileIDImage[ thisTile ], (col * 32, row * 32))
| 0
| 1
| 0
| 0
| 0
| 0
|
Currently I have:
def func(points): #Input is a matrix with n lines and 2 columns.
centroid = numpy.mean(points, axis=0)
sum = 0
for point in points:
x = point[0] - centroid[0]
y = point[1] - centorid[1]
sum += x**2 + y**2
return math.sqrt(sum)
| 0
| 0
| 0
| 0
| 1
| 0
|
I’m looking for a simple example of how to write an internal DSL using Ruby and regex pattern matching. Similar to how Sinatra handles routes
get '/say/*/to/*' do
# Some Ruby code here
end
Also similar to how Cucumber handles step definitions:
Given /^I have (\d+) cucumbers in my belly$/ do |cukes|
# Some Ruby code here
end
I’m not interested in builders, or fluent method chaining. Basically I want a Ruby class which looks something like this:
class SpecVocabulary
match ‘pattern’ do
# Some Ruby code here
end
# Or, using a different keyword
phrase ‘pattern’ do
# Some Ruby code here
end
end
What I’m struggling with is wiring-up the code which makes the SpecVocabular class automatically match patterns and fill out it’s data.
I’m hoping someone has a simple example of how to do this, I’m trying to avoid having to dive in the source for Sinatra and Cucumber.
Incidentally I already have the natural language define, though I omitted it purposely.
| 0
| 1
| 0
| 0
| 0
| 0
|
I redefined some maths functions (so that they're faster -ie: less accurate-, or use templates). I put these functions in a namespace and they work just fine.
It happens often, though, that I forget to call functions from my namespace (ie: I forget to write mymath::cos or using mymath::cos; when I want to call cos), and it's pretty tough to find out where I forgot it (until now I found it out only by profiling).
Given that
I only include standard math.h or cmath headers within my math header, and that
I need to include standard math headers (because some of my functions are just wrappers for standard one, and I want them to be inline or they're templated),
is there a portable way to hide standard math function so that a compile error is reported, if global namespace (ie: without a namespace) math functions are used?
A solution could be putting an using namespace mymath; at the bottom of my math header file, but this solution doesn't seem that great: it breaks the whole purpose of namespaces; I'd prefer having to explicity say whether to use a function from mymath or from std so that I am forced to choose between a fester or a more accurate function without the risk of forgetting about it.
EDIT:
Many answers say that if I use cos from global namespace (without using std nor mymath), and include cmath (and not math.h), compilation should fail.
I don't know what the standard says about it, but:
#include <cmath>
int main( ) {
cos( M_PI );
return 0;
}
compiles fine with GNU GCC (g++) 4.5.1 (and older versions).
| 0
| 0
| 0
| 0
| 1
| 0
|
Are floating point calculations, which use compile-time constant integers, performed during compile-time or during run-time? For example, when is the division operation calculated in:
template <int A, int B>
inline float fraction()
{
return static_cast<float>(A) / B;
}
| 0
| 0
| 0
| 0
| 1
| 0
|
In my research, I am generating discrete planes that are intended to represent fractures in rock. The orientation of a fracture plane is specified by its dip and dip direction. Knowing this, I also know the components of the normal vector for each plane.
So far, I have been drawing dip and dip direction independently from normal distributions. This is OK, but I would like to add the ability to draw from the Fisher distribution.
The fisher distribution is described
HERE
Basically, I want to be able to specify an average dip and dip direction (or a mean vector) and a "fisher constant" or dispersion factor, k, and draw values randomly from that orientation distribution.
Additional Info: It seems like the "Von Mises-Fisher distribution" is either the same as what I've been calling the "Fisher distribution" or is somehow related. Some info on the Von Mises-Fisher distribution:
As you can see, I've done some looking into this, but I admit that I don't fully understand the mathematics. I feel like I'm close, but am not quite getting it... Any help is much appreciated!
If it helps, my programming is in FORTRAN.
| 0
| 0
| 0
| 0
| 1
| 0
|
What does the following loop do?
k = 0
while(b!=0):
a = a^b
b = (a & b) << 1
k = k + 1
where a, b and k integers.
Initially a = 2779 and b = 262 then what will be the value of k after the termination of the loop?
I'd be happy if you people try solving the problem manually rather than programmatically.
EDIT : Dropping the tags c and c++. How can I solve the problem manually?
| 0
| 0
| 0
| 0
| 1
| 0
|
I have numbers in range 1-62
I want to be able to "crypt" them, so that it's hard to guess they are generated in some order.
So, it should be some mapping, for example
1->35
2->19
3->61
...
so that I have 1 to 1 mapping, 100% reversible.
I can hardcode mapping, but I would prefer math solution to that, some kind of formula which takes number as argument, and produces number in range 1-62, and does NOT generate duplicates. Is there any chance this formula exists?
Just for history, validation script:
<?
$test = array();
$val = 37;
for($i=0;$i<62;$i++)
{
if($test[($i*$val)%62])
{
print("Collision: $i ".$test[($i*$val)%62]."<br/>");
}
$test[($i*$val)%62] = $i;
print("$i => ".(($i*$val)%62)."<br/>");
}
?>
Update:
Here are IDs generated thanks to these answers:
qpOLHk
NMb84H
aI740D
x5urn0
UsROKn
hPeb7K
EcByu7
1zYVRu
oWlieR
LjIFBe
8G52YB
v3splY
SqPMIl
fNc95I
Cazws5
ZxWTPs
mUjgcP
JhGDzc
6E30Wz
Sweeeeeet :-)
| 0
| 0
| 0
| 0
| 1
| 0
|
I am able to measure my distance to a set of (about 6 or 7) fixed but unknown points from many positions.
The difference in position between measurements is also unknown.
I believe that I should be able to work out the relative position of the fixed points, and therefore where I measured from and the path I took.
I have looked at the wiki page for trilateration, but it only gives examples working from known points.
| 0
| 0
| 0
| 0
| 1
| 0
|
I'm computing an LDA (linear discriminant analysis) transform, for an application I'm working on, and I've been following these notes (starting at page 36, especially slide 47 in green).
I'm doing this in Python (with numpy and scipy), and this is what I have come up with:
import numpy as np
from scipy.linalg import sqrtm
...
sw_inv_sqrt = np.linalg.inv(sqrtm(self.sigma_within))
self.d, self.v = np.linalg.eig(
np.dot(
np.dot(sw_inv_sqrt, self.sigma_between),
sw_inv_sqrt
))
self.v = np.dot(sw_inv_sqrt, self.v)
I know that this implementation is correct as I have compared it to others. My concern is whether this is good solution in the numerical sense. In comparing my solution to others, they match only to about 6 decimal places. Is there a better way to do this numerically?
| 0
| 0
| 0
| 0
| 1
| 0
|
I am writing a Java application to calculate interest. The formulas for Simple, Compound, and Continuously Compounded interest use years to calculate the amount accumulated, but I want to use days so that my software updates more frequently. What formulas should I use? This is an Android project with JodaTime implemented for handling dates.
| 0
| 0
| 0
| 0
| 1
| 0
|
I'm trying to find the best way to normalize consistently.
Basically I have a certain number of instances, each one with a certain number of attributes with floating values:
For example:
At1 At2 At3
0.1 0.3 3.0
0.1 4.5 2.1
...
And I want to map each attribute to integer values, trying to be consistent with the data.
I tried for example to simply , for each attribute, divide the difference between the max value and the min value for that attribute, dividing it into an arbitrary value like 10, and then map all the double values of each attributes to the index of it's corresponding interval, and by doing so, normalizing my attributes to integer values between 1 and ten...
But I would like an approach that would use the shortest number possible of intervals for each attributes without losing consistency, for example, If I have one attribute with three possible values: 1.2, 3.5 and 223.3 by my approach using for example intervals of 10 possible values I would have a ton of unnecessary intervals for that attribute, and a LOT of wasted space...
Any suggestions?
| 0
| 0
| 0
| 0
| 1
| 0
|
List<Man> list=new ArrayList<Man>();
Man manA = new Man(29); // constructor parameter is age, use manA.age to get 29
list.add(manA);
Man manB = new Man(23);
list.add(manB);
Man manC = new Man(42);
list.add(manC);
Man manD = new Man(38);
list.add(manD);
I want get the maximum age element manC in list,
What's the best(fastest) way to do this?
| 0
| 0
| 0
| 0
| 1
| 0
|
Suppose we are given data in a semi-structured format as a tree. As an example, the tree can be formed as a valid XML document or as a valid JSON document. You could imagine it being a lisp-like S-expression or an (G)Algebraic Data Type in Haskell or Ocaml.
We are given a large number of "documents" in the tree structure. Our goal is to cluster documents which are similar. By clustering, we mean a way to divide the documents into j groups, such that elements in each looks like each other.
I am sure there are papers out there which describes approaches but since I am not very known in the area of AI/Clustering/MachineLearning, I want to ask somebody who are what to look for and where to dig.
My current approach is something like this:
I want to convert each document into an N-dimensional vector set up for a K-means clustering.
To do this, I recursively walk the document tree and for each level I calculate a vector. If I am at a tree vertex, I recur on all subvertices and then sum their vectors. Also, whenever I recur, a power factor is applied so it does matter less and less the further down the tree I go. The documents final vector is the root of the tree.
Depending on the data at a tree leaf, I apply a function which takes the data into a vector.
But surely, there are better approaches. One weakness of my approach is that it will only similarity-cluster trees which has a top structure much like each other. If the similarity is present, but occurs farther down the tree, then my approach probably won't work very well.
I imagine there are solutions in full-text-search as well, but I do want to take advantage of the semi-structure present in the data.
Distance function
As suggested, one need to define a distance function between documents. Without this function, we can't apply a clustering algorithm.
In fact, it may be that the question is about that very distance function and examples thereof. I want documents where elements near the root are the same to cluster close to each other. The farther down the tree we go, the less it matters.
The take-one-step-back viewpoint:
I want to cluster stack traces from programs. These are well-formed tree structures, where the function close to the root are the inner function which fails. I need a decent distance function between stack traces that probably occur because the same event happened in code.
| 0
| 1
| 0
| 0
| 0
| 0
|
Am learning C and thought that Project Euler problems would be a fun and interesting way to learn (and would kill 2 birds with 1 stone because it would keep me thinking about maths as well) but I've hit a snag.
I have (what I think is) a good (if simple) algorithm for finding the largest prime factor of a number. It works (as far as I have tested it), but the PE question uses 600851475143 as it's final question. I have tried to use doubles and such, but I can never seem to find both a modulo and a division operator. Any help would be greatly appreciated.
Code attached is before I started to make it work with doubles (or any other type):
#include<stdio.h>
#include <math.h>
void main() {
int target, divisor, answer;
target = 375;
divisor = 2;
answer = -1;
answer = factorise (target,divisor);
printf("Answer to Euler Problem 3: %i
", answer);
}
int factorise(number, divisor) {
int div;
while (divisor < number) {
div = divide(number,divisor);
if (div) {number = div;}
else {divisor++;}
}
return divisor;
}
int divide(a,b) {
if (a%b) {return 0;}
else {return a/b;}
}
| 0
| 0
| 0
| 0
| 1
| 0
|
I have seen this bug in many blog posts:
http://atifsiddiqui.blogspot.com/2010/11/windows-calculator-bug.html
Is this bug a code bug or a mathematical imprecision ?
I am wondering if its really a bug, How it got undetected for years ?
What should I take care to make sure that it doesn't happen in my custom caculator program.
| 0
| 0
| 0
| 0
| 1
| 0
|
running the below script I receive :
line 8: ((: i = 0 : syntax error:
invalid arithmetic operator (error
token is " ")
Any idea what is wrong? Can it be the I edit with text editor on an iMac? something to do maybe with a CR?
domains=( yourdomain.com yourdomain2.com )
sqldbs=( yourdb1 yourdb2 )
opath=$HOME/backup/
mysqlhost=mysqlhostname
username=mysqlusername
password=mysqlpassword
suffix=$(date +%m-%d-%Y)
for (( i = 0 ; i < ${#domains[@]} ; i++ ))
do
cpath=$opath${domains[$i]}
if [ -d $cpath ]
then
filler="just some action to prevent syntax error"
else
echo Creating $cpath
mkdir -p $cpath
fi
mysqldump -c -h $mysqlhost --user $username --password=$password ${sqldbs[$i]} > ${cpath}/${sqldbs[$i]}_$suffix.sql
done
| 0
| 0
| 0
| 0
| 1
| 0
|
What is good practice for error handling in math-related functions? I'm building up a library (module) of specialized functions and my main purpose is to make debugging easier for the code calling these functions -- not to make a shiny user-friendly error handling facility.
Below is a simple example in VBA, but I'm interested in hearing from other languages as well. I'm not quite sure where I should be returning an error message/status/flag. As an extra argument?
Function AddArrays(arr1, arr2)
Dim i As Long
Dim result As Variant
' Some error trapping code here, e.g.
' - Are input arrays of same size?
' - Are input arrays numeric? (can't add strings, objects...)
' - Etc.
' If no errors found, do the actual work...
ReDim result(LBound(arr1) To UBound(arr1))
For i = LBound(arr1) To UBound(arr1)
result(i) = arr1(i) + arr2(i)
Next i
AddArrays = result
End Function
or something like the following. The function returns a boolean "success" flag (as in the example below, which would return False if the input arrays weren't numeric etc.), or an error number/message of some other type.
Function AddArrays(arr1, arr2, result) As Boolean
' same code as above
AddArrays = booSuccess
End Function
However I'm not too crazy about this, since it ruins the nice and readable calling syntax, i.e. can't say c = AddArrays(a,b) anymore.
I'm open to suggestions!
| 0
| 0
| 0
| 0
| 1
| 0
|
Thing is I have a file that has room for metadata. I want to store a hash for integrity verification in it. Problem is, once I store the hash, the file and the hash along with it changes.
I perfectly understand that this is by definition impossible with one way cryptographic hash methods like md5/sha.
I am also aware of the possibility of containers that store verification data separated from the content as zip & co do.
I am also aware of the possibility to calculate the hash separately and send it along with the file or to append it at the end or somewhere where the client, when calculating the hash, ignores it.
This is not what I want.
I want to know whether there is an algorithm where its possible to get the resulting hash from data where the very result of the hash itself is included.
It doesn't need to be cryptographic or fullfill a lot of criterias. It can also be based on some heuristics that after a realistic amount of time deliver the desired result.
I am really not so into mathematics, but couldn't there be some really advanced exponential modulo polynom cyclic back-reference devision stuff that makes this possible?
And if not, whats (if there is) the proof against it?
The reason why i need tis is because i want (ultimately) to store a hash along with MP4 files. Its complicated, but other solutions are not easy to implement as the file walks through a badly desigend production pipeline...
| 0
| 0
| 0
| 0
| 1
| 0
|
I am developing some linear algebra code that that is templated on the
matrix coefficient type. One of the possible types is a class to do
modular arithmetic, naively implemented as follows:
template<typename val_t> // `val_t` is an integer type
class Modular
{
val_t val_;
static val_t modulus_;
public:
Modular(const val_t& value) : val_(value) { };
static void global_set_modulus(const val_t& modulus) { modulus_ = modulus; };
Modular<val_t>& operator=(const Modular<val_t>& other) { val_ = other.val_; return *this; }
Modular<val_t>& operator+=(const Modular<val_t>& other) { val_ += other.val_; val_ %= modulus_; return *this; }
Modular<val_t>& operator-=(const Modular<val_t>& other) { val_ -= other.val_; val_ %= modulus_; return *this; }
Modular<val_t>& operator*=(const Modular<val_t>& other) { val_ *= other.val_; val_ %= modulus_; return *this; }
Modular<val_t>& operator/=(const Modular<val_t>& other) { val_ *= other.inverse().val_; val_ %= modulus_; return *this; }
friend Modular<val_t> operator+(const Modular<val_t>& a, const Modular<val_t>& b) { return Modular<val_t>((a.val_ + b.val_) % Modular<val_t>::modulus_); };
friend Modular<val_t> operator-(const Modular<val_t>& a, const Modular<val_t>& b) { return Modular<val_t>((a.val_ - b.val_) % Modular<val_t>::modulus_); };
// ...etc.
};
However, when the program runs with the Modular<int> coefficients, it is several
times slower than when it runs with int coefficients.
What are the things that I should change in the "Modular" class in
order to gain maximum performance?
For instance, is it possible to optimize expressions like a*b + c*d
to (a.val_*b.val_ + c.val_*d.val_) % modulus, and instead of the obvious:
(((a.val_*b.val_) % modulus) + ((c.val_*d.val_ % modulus) % modulus) % modulus)
| 0
| 0
| 0
| 0
| 1
| 0
|
Alright, so this is how I am doing it:
float xrot = 0;
float yrot = 0;
float zrot = 0;
Quaternion q = new Quaternion().fromRotationMatrix(player.model.getRotation());
if (q.getW() > 1) {
q.normalizeLocal();
}
float angle = (float) (2 * Math.acos(q.getW()));
double s = Math.sqrt(1-q.getW()*q.getW());
// test to avoid divide by zero, s is always positive due to sqrt
// if s close to zero then direction of axis not important
if (s < 0.001) {
// if it is important that axis is normalised then replace with x=1; y=z=0;
xrot = q.getXf();
yrot = q.getYf();
zrot = q.getZf();
// z = q.getZ();
} else {
xrot = (float) (q.getXf() / s); // normalise axis
yrot = (float) (q.getYf() / s);
zrot = (float) (q.getZf() / s);
}
But it doesn't seem to work when I try to put it into use:
player.model.addTranslation(xrot * player.speed, 0, zrot * player.speed);
AddTranslation takes 3 numbers to move my model by than many spaces (x, y, z), but hen I give it the numbers above it doesn't move the model in the direction it has been rotated (on the XZ plane)
Why isn't this working?
Edit: new code, though it's about 45 degrees off now.
Vector3 move = new Vector3();
move = player.model.getRotation().applyPost(new Vector3(1,0,0), move);
move.multiplyLocal(-player.speed);
player.model.addTranslation(move);
| 0
| 0
| 0
| 0
| 1
| 0
|
I jumped into Processing (the language) today. I've been trying to implement a line without the line() function. In other words, I'm trying to replicate the line() function with my own code. I'm almost there, but not. (There's a screen, and you can click around, and this function connects those clicks with lines.)
There are four different line slopes I'm dealing with (m>1, 0
If you could just glance at the following code, and tell me where I've gone wrong, I'd be grateful.
int xStart = -1; // Starting x and y are negative.
int yStart = -1; // No lines are drawn when mouseReleased() and x/y are negative.
boolean isReset = false; // Turns true when 'r' is pressed to reset polygon chain.
int clickCounter = 0; // Changes background color every 10 clicks (after c is pressed).
color backgroundColor = 0; // Starting background color. Changed occasionally.
color lineColor = 255;
int weight = 1;
void setup() {
size(800, 800); // Initial size is 800x800
background(backgroundColor); // ...background is black.
smooth();
stroke(lineColor); //... lines/points are white.
strokeWeight(weight);
}
void draw() {
}
void mousePressed(){
clickCounter++;
}
void mouseReleased(){ // mouseReleased used instead of mousePressed to avoid dragged clicks.
point(mouseX, mouseY); // Draws white point at clicked coordinates.
if((xStart < 0 && yStart < 0) || isReset){ // If x/y negative or if r was pressed, set start points and return. No line drawn.
xStart = mouseX;
yStart = mouseY;
isReset = false; // Reset isReset to false.
return;
}
// Sends starting and ending points to createLine function.
createLine(xStart, yStart, mouseX, mouseY); // createLine(...) - Creates line from start point to end point.
xStart = mouseX; // Start point = last click location. End point = Current click location.
yStart = mouseY; // Sets starting coordinates for next click at current click point.
}
void keyPressed(){
if(key == 'x') // EXTRA CREDIT ADDITION: If x is pressed -> Exit program.
exit();
else if(key == 'c'){ // EXTRA CREDIT ADDITTION: If c pressed -> Set background black to clear all lines/points on screen.
if(clickCounter > 10){
backgroundColor = color(random(255), random(255), random(255)); // EXTRA CREDIT ADDITION: If cleared and clickCounter is greater
clickCounter = 0; // ...than 10, background changes to random color.
}
background(backgroundColor);
xStart = -1; // Must set points negative so line is not drawn after next new point is made (since there will only be one point on the screen).
yStart = -1;
}
else if(key == 'r'){ // If r pressed -> Reset: Next click will create new point that isn't connected with line to current points.
isReset = true;
lineColor = color(random(255), random(255), random(255)); // EXTRA CREDIT ADDITION: When dot chain is "reset", line changes color.
weight = (int)random(10);
strokeWeight(weight); // EXTRA CREDIT ADDITION: ...and line/dot thickness changes.
stroke(lineColor);
}
else
return;
}
// createLine(): Function which draws line from (x0,y0) to (x1,y1).
void createLine(int x0, int y0, int x1, int y1){
// 1) Line function draws from left to right. (Does not work right to left.) Check and swap points if ending point is left of starting point.
if(x1 < x0){
print("LEFT TO RIGHT SWITCH.
");
createLine(x1, y1, x0, y0); // Drawing the line left to right cuts the number of line types we have to deal with to 4 regions.
return; // Regions: slope > 1; 0 < slope < 1; -1 < slope < 0; slope < -1.
}
// Declare/Initialize data needed to draw line with midpoint algorithm.
int dx = x1 - x0;
int dy = y1 - y0; //dy = Negative when y0 is lower on screen than y2, because origin is top left.
print(y0 + " " + x0 + " " +y1 + " " + x1+ " x y
");
print(dy + " " + dx + " dx dy
");
// Handle vertical & horizontal lines...
if(dx == 0 || dy == 0){ // If slope is vertical or horizontal, create line with simple function.
while(y1 != y0){ // If vertical -> Paint by incrementing/decrementing y until points connect.
if(y1 > y0){ // If new point is above -> Draw upwards.
y0 = y0 + 1;
point(x0, y0);
}
else{ // It new point below -> Draw downwards.
y0 = y0 - 1;
point(x0, y0);
}
}
while(x1 != x0){ // If horizontal -> Paint by incrementing x until points connect (will be left to right line always).
x0 = x0 + 1;
point(x0, y0);
}
return;
}
// Handle slanted lines...
double tempDX = x1 - x0;
double tempDY = y1 - y0; // Had to create dx and dy as doubles because typecasting dy/dx to a double data type wasn't working.
double m = (-tempDY / tempDX); // m = line slope. (Note - The dy value is negative because positive y is downwards on the screen.)
print("SLOPE CALCULATED: " + m + "
");
int deltaN = (2 * -dx); // deltaX is the amount to increment d after choosing the next pixel on the line.
int deltaNE = (2 * (-dy - dx)); // ...where X is the direction moved for that next pixel.
int deltaE = (2 * -dy); // deltaX variables are used below to plot line.
int deltaSE = (2 * (dy + dx));
int deltaS = (2 * dx);
int x = x0;
int y = y0;
int d = 0; // d = Amount d-value changes from pixel to pixel. Depends on slope.
int region = 0; // region = Variable to store slope region. Different regions require different formulas.
if(m > 1){ // if-statement: Initializes d, depending on the slope of the line.
d = -dy - (2 * dx); // If slope is 1-Infiniti. -> Use NE/N initialization for d.
region = 1;
}
else if(m == 1)
region = 2;
else if(m > 0 && m < 1){
d = (2 * -dy) - dx; // If slope is 0-1 -> Use NE/E initialization for d.
region = 3;
}
else if(m < 0 && m > -1){
d = (2 * dy) + dx; // If slope is 0-(-1) -> Use E/SE initliazation for d.
region = 4;
}
else if(m == -1)
region = 5;
else if(m < -1){
d = dy + (2 * dx); // If slope is (-1)-(-Infiniti) -> Use SE/S initialization for d.
region = 6;
}
while(x < x1){ // Until points are connected...
if(region == 1){ // If in region one...
if(d <= 0){ // and d<=0...
d += deltaNE; // Add deltaNE to d, and increment x and y.
x = x + 1;
y = y - 1;
}
else{
d += deltaN; // If d > 0 -> Add deltaN, and increment y.
y = y - 1;
}
}
else if(region == 2){
x = x + 1;
y = y - 1;
}
else if(region == 3){
if(d <= 0){
d += deltaE;
x = x + 1;
}
else{
d += deltaNE;
x = x + 1;
y = y - 1;
}
}
else if(region == 4){
if(d <= 0){
d += deltaSE;
x = x + 1;
y = y + 1;
}
else{
d += deltaE;
x = x + 1;
}
}
else if(region == 5){
x = x + 1;
y = y + 1;
}
else if(region == 6){
if(d <= 0){
d += deltaSE;
x = x + 1;
y = y + 1;
}
else{
d += deltaS;
y = y + 1;
}
}
point(x, y);
}
return;
}
| 0
| 0
| 0
| 0
| 1
| 0
|
I've written a simple little helper method whoch calculates the distance from a point to a plane. However, it seems to be returning nonsensical results. The code i have for creating a plane is thus:
Plane = new Plane(vertices.First().Position, vertices.Skip(1).First().Position, vertices.Skip(2).First().Position);
Fairly simple, I hope you'll agree. It creates an XNA plane structure using three points.
Now, immediately after this I do:
foreach (var v in vertices)
{
float d = Math.Abs(v.ComputeDistance(Plane));
if (d > Constants.TOLERANCE)
throw new ArgumentException("all points in a polygon must share a common plane");
}
Using the same set of vertices I used to construct the plane, I get that exception thrown! Mathematically this is impossible, since those three points must lie on the plane.
My ComputeDistance method is:
public static float ComputeDistance(this Vector3 point, Plane plane)
{
float dot = Vector3.Dot(plane.Normal, point);
float value = dot - plane.D;
return value;
}
AsI understand it, this is correct. So what could I be doing wrong? Or might I be encountering a bug in the implementation of XNA?
Some example data:
Points:
{X:0 Y:-0.5000001 Z:0.8660254}
{X:0.75 Y:-0.5000001 Z:-0.4330128}
{X:-0.75 Y:-0.5000001 Z:-0.4330126}
Plane created:
{Normal:{X:0 Y:0.9999999 Z:0} D:0.5} //I believe D should equal -0.5?
Distance from point 1 to plane:
1.0
| 0
| 0
| 0
| 0
| 1
| 0
|
I'm hoping someone has come across this problem before too.
I am trying to use visual studio to develop for Linux with G++.
I am trying to include math.h and use tanf()
If I compile with the g++ compiler, "arm-none-linux-gnueabi-g++", everything works
but if I add this include directory, which the docs say is the right one, and
"CodeSourcery\Sourcery G++ Lite\arm-none-linux-gnueabi\libc\usr\include\"
then include math.h,
visual studio does not recognize any of the math functions, namely tanf().
anyone have any idea why?
thanks for any help.
edit:
the same app successfully compiles with this command line:
arm-none-linux-gnueabi-g++ -o test main.cpp "-I%PALMPDK%\include" "-I%PALMPDK%\include\SDL" "-L%PALMPDK%\device\lib" -Wl,--allow-shlib-undefined -lSDL -lGLESv2 -lpdl
| 0
| 0
| 0
| 0
| 1
| 0
|
It is stated, that to rotate a line by a certain angle, you multiply its end point coordinates by the matrix ({Cos(a), Sin(a)} {-Sin(a) Cos(a)}), where a is rotation angle. The resulting two numbers in matrix will be x and y coordinates of rotated line's end point. Rotation goes around line's start point.
Simplifying it, new coordinates will be {x*Cos(a) - y*Sin(a)} for x and {x*Sin(a) + y*Cos(a)} for y.
Task is to rotate a triangle, using this method. But the following code that uses this method, is giving out some crap instead of rotated image (twisted form of original triangle, rotated by "random" angle):
x0:=200;
y0:=200;
bx:=StrToInt(Edit1.Text);
by:=StrToInt(Edit2.Text);
cx:=StrToInt(Edit4.Text);
cy:=StrToInt(Edit5.Text);
a:=StrToInt(Edit3.Text);
//Original triangle
Form1.Canvas.Pen.Color:=clBlue;
Form1.Canvas.MoveTo(x0,y0);
Form1.Canvas.LineTo(bx,by);
Form1.Canvas.LineTo(cx,cy);
Form1.Canvas.LineTo(x0,y0);
//New triangle
Form1.Canvas.Pen.Color:=clGreen;
Form1.Canvas.MoveTo(x0,y0);
b1x:=Round(bx*cos(a*pi/180)-by*sin(a*pi/180));
b1y:=Round(bx*sin(a*pi/180)+by*cos(a*pi/180));
c1x:=Round(cx*cos(a*pi/180)-cy*sin(a*pi/180));
c1y:=Round(cx*sin(a*pi/180)+cy*cos(a*pi/180));
Form1.Canvas.LineTo(b1x,b1y);
Form1.Canvas.MoveTo(x0,y0);
Form1.Canvas.LineTo(c1x,c1y);
Form1.Canvas.LineTo(b1x,b1y);
end;
Well, I'm out of ideas. What am I doing wrong?
Thanks for your time.
| 0
| 0
| 0
| 0
| 1
| 0
|
Its available for me only log(base "e"), sin, tan and sqrt (only square root) functions and the basic arithmetical operators (+ - * / mod). I have also the "e" constant.
I'm experimenting several problems with Deluge (zoho.com) for these restrictions. I must implement exponentiation of rational (fraction) bases and exponents.
| 0
| 0
| 0
| 0
| 1
| 0
|
I would like to apply RBF neural networks to teach my system.
I have a system with an input:
| 1 2 3 4 5 6 ... 32 | 33 |
| 1000 0001 0010 0100 1000 1000 ... 0100 | 0 0 1 |
You have to read this without the "|" character. I just wanted you to see that the last three elements in the input are staying together. The result have to be a number between 1-32, which has the value "1000" in the input. In my training set I will always have a result for an array of this kind. What kind of functions can I use for the teaching algorithm? Can you point me please to the right way?
If you can't understand my description please don't hesitate to ask about it. Thank you guys for your help!
| 0
| 0
| 0
| 1
| 0
| 0
|
For a beginner, which is the best book to start with for studying Bayesian Networks?
| 0
| 0
| 0
| 1
| 0
| 0
|
I'm not a mathematician, so I'll try to describe this in a layperson's terms.
I'm trying to take two time series, which could represent any variable quantity, maximum daily temperature, stock price high of the day, etc. These would be multiplied by a factor that would make their maxima and minima correspond. (E.g., two temperature series might range between different coldest and warmest temperatures, but in both I'd treat coldest as 0% and warmest as 100%.)
Given this, I want to find out what relative shift in their start times would produce the "most" correlation. That is, the longest sample period with a "high" correlation. (I know that's a bit fuzzy.)
As a simple example, given last year's temperatures for several cities, it might choose two cities that both had a period of several weeks in which every other day had a maximum temperature that was 2/3 of the preceding day. This didn't necessarily start for both cities on the same day. That's where the time shifting trials come in.
A pointer to a discussion, pseudo code, or actual utility library would be good.
| 0
| 0
| 0
| 0
| 1
| 0
|
I'm trying to write a report to recommend moving transaction logs to a separate physical drive but I need to provide some numbers. I have some queries from a profile that was done last month. I'm trying to determine the reduction % of the duration. I know that it can't be 100% exact but a very close numbert will suffice.
Query 1
Reads: 325229284
Writes: 85989
Duration: 840732
Query 2
Reads: 558955611
Writes: 87066
Duration: 1015697
Query 3
Reads: 422966141
Writes: 85087
Duration: 918225
currently reads and writes happen on the same drive. I want to move them so reads are one drive and writes are another. I tried to figure it out assuming writes are 20% slower than reads but didn't average in seek times. I was getting between 7%-15% but have no idea if those figures are correct. Assuming drive seek time is avg 1ms.
| 0
| 0
| 0
| 0
| 1
| 0
|
I am sorry, if my question sounds stupid :)
Can you please recommend me any pseudo code or good algo for LSI implementation in java?
I am not math expert. I tried to read some articles on wikipedia and other websites about
LSI ( latent semantic indexing ) they were full of math.
I know LSI is full of math. But if i see some source code or algo. I understand things more
easily. That's why i asked here, because so many GURU are here !
Thanks in advance
| 0
| 0
| 0
| 0
| 1
| 0
|
I often have to search many words (1000+) in many documents (million+). I need position of matched word (if matched).
So slow pseudo version of code is
for text in documents:
for word in words:
position = search(word, text)
if position:
print word, position
Is there any fast Python module for doing this? Or should I implement something myself?
| 0
| 1
| 0
| 0
| 0
| 0
|
Having dramatically different step sizes, and not much data. We have data like >--4-6----3-9----4-7----9-3----4-1----> ( - is step here ) and in real life this data is looped in a circle. What polynomials/formulas can help me with interpolation of such data? Will Bezier work?
| 0
| 0
| 0
| 0
| 1
| 0
|
Hallo,
How can I calculate a current time moment + exactly one week?
The same with month.
Thanks.
| 0
| 0
| 0
| 0
| 1
| 0
|
I am trying to put some asm code into a latex document, onfurtunatly pdflatex treats the $ signs within my document as math env (which I do not want). On the other side I'd still like to use that fancy linebreak arrow (which uses math env to display it).
\lstset{
texcl=false,
mathescape=false,
..,
prebreak = \raisebox{0ex}[0ex][0ex]{ensuremath{\hookleftarrow}}
}
example snap:
CTRL_WD_12 equ $303400
CTRL_WD_34 equ $220000
CTRL_WD_56 equ $000000
CTRL_WD_78 equ $000000
thanks for any help.
| 0
| 0
| 0
| 0
| 1
| 0
|
I've been hunting on the net periodically for several months for an answer to this with no joy. Grateful if anyone can shed any light..
I'm interested in work that's been done on simulating the human brain. I could of course mean many things by that. Here's what I do mean, followed by what I don't mean:
I AM interested in simulations of how we think and feel. I'm not talking about down to the level of neurons, but more simulation of the larger modules that are involved. For example one might simulate the 'anger' module as a service that measures the degree one has been disrespected (in some system of representation) and outputs an appropriate measure of anger (again in some system of representation).
I am NOT interested in projects like the Blue Brain etc, where accurate models of neuron clusters are being built. I'm interested in models operating at much higher levels of abstraction, on the level of emotional modules, cognitive reasoning systems etc.
I'm also NOT interested in AI projects that take as their inspiration or paradigm human mechanisms, like Belief-Desire-Intention systems, but which are not actually trying to replicate human behavior. Interesting though these systems are, I'm not interested in making effective systems, but effectively modelling human thought and emotion.
I've been searching far and wide, but all I've found are papers from the 60s like this one:
Computer Simulation of Human Interaction in Small Groups
It almost appears to me as if psychologists were excited by simulating brains when computers were first available, but now don't do it at all?
Can anyone point me in the direction of more recent research/efforts, if there have been any?
| 0
| 1
| 0
| 0
| 0
| 0
|
Okay so I need to make a basic activity (working Flash/as3) that simulates very basic weighing scales. All the objects that go on to the scales are the same weight.
If you imagine the classic weighing scales (http://www.metalminnie.co.uk/mm1/scales-S1055936773790.JPG) - we are dragging/dropping stuff on to the sides and animating accordingly.
I don't want anything fancy, just the maths required to affect the scales according to how many objects are on each side.
What I'm looking for is probably the angle of rotation of the horizontal arm. Any pointers?
| 0
| 0
| 0
| 0
| 1
| 0
|
suppose I have the following 2 random variables :
X where mean = 6 and stdev = 3.5
Y where mean = -42 and stdev = 5
I would like to create a new random variable Z based on the first two and knowing that : X happens 90% of the time and Y happens 10% of the time.
It is easy to calculate the mean for Z : 0.9 * 6 + 0.1 * -42 = 1.2
But is it possible to generate random values for Z in a single function?
Of course, I could do something along those lines :
if (randIntBetween(1,10) > 1)
GenerateRandomNormalValue(6, 3.5);
else
GenerateRandomNormalValue(-42, 5);
But I would really like to have a single function that would act as a probability density function for such a random variable (Z) that is not necessary normal.
sorry for the crappy pseudo-code
Thanks for your help!
Edit : here would be one concrete interrogation :
Let's say we add the result of 5 consecutives values from Z. What would be the probability of ending with a number higher than 10?
| 0
| 0
| 0
| 0
| 1
| 0
|
Mathematically we can solve it like Given Amount / Total Amount * 100 to get the percentage difference. But what I need is to compare 2 Integer Arrays (in C# Win App) and get the percentage of the difference.
Like :
1 -----> -2
2 -----> 3
3 -----> 7
4 -----> 456
5 -----> 13
These two columns are 2 Integer Arrays and I should get the difference between them.
How can I get this? A mathematical answer or an algorithm, whatever can be used to solve the problem.
| 0
| 0
| 0
| 0
| 1
| 0
|
I have a function which calculates the acoustic strength of a fish depending on the incident angle of the wavefront on the fish. I also have some in situ measurements of acoustic strength. What I'm trying to do is figure out which normal distribution of angles results in the model data matching up most closely with the in situ data.
To do this, I'm trying to use the Matlab function fmincon to minimize the following function:
function f = myfun(x)
TS_krm = KRM(normrnd(x(1),x(2),100,1), L);
f = sum((TS_insitu - TS_krm).^2);
So what this function does is calculates the sum of squared residuals, which I want to minimize. To do this, I try using fmincon:
x = fmincon(@myfun, [65;8], [], [], [], [], [0;0], [90;20], [], options);
Thus, I'm using a starting orientation with a mean of 65 degrees and a standard deviation of 8. I'm also setting the mean angle bounds to be from 0 to 90 degrees and the standard deviation bounds to be from 0 to 20 degrees.
Yet it doesn't seem to be properly finding the mean and standard deviation angles which minimize the function. Usually it outputs something right around N(65,8), almost like it isn't really trying many other values far from the starting points.
Any ideas on what I can do to make this work? I know I can set the TolX and TolFun settings, but I'm not really sure what those do and what effect they'd have. If it helps, the typical values that I'm dealing with are usually around -45 dB.
Thanks!
| 0
| 0
| 0
| 0
| 1
| 0
|
I've been searching the net for ~3 hours but I couldn't find a solution yet. I want to give a precomputed kernel to libsvm and classify a dataset, but:
How can I generate a precomputed kernel? (for example, what is the basic precomputed kernel for Iris data?)
In the libsvm documentation, it is stated that:
For precomputed kernels, the first element of each instance must be
the ID. For example,
samples = [[1, 0, 0, 0, 0], [2, 0, 1, 0, 1], [3, 0, 0, 1, 1], [4, 0, 1, 1, 2]]
problem = svm_problem(labels, samples)
param = svm_parameter(kernel_type=PRECOMPUTED)
What is a ID? There's no further details on that. Can I assign ID's sequentially?
Any libsvm help and an example of precomputed kernels really appreciated.
| 0
| 0
| 0
| 1
| 0
| 0
|
What is the best matrix multiplication algorithm? What means 'the best'for me? It means the fastest and ready for todays machines.
Please give links to pseudocode if you can.
| 0
| 0
| 0
| 0
| 1
| 0
|
Can anyone explain to me in detail how this log2 function works:
inline float fast_log2 (float val)
{
int * const exp_ptr = reinterpret_cast <int *> (&val);
int x = *exp_ptr;
const int log_2 = ((x >> 23) & 255) - 128;
x &= ~(255 << 23);
x += 127 << 23;
*exp_ptr = x;
val = ((-1.0f/3) * val + 2) * val - 2.0f/3; // (1)
return (val + log_2);
}
| 0
| 0
| 0
| 0
| 1
| 0
|
I have values for the following variables::
x0,y0,z0 = coords of the first selection (intended to be center of sphere)
x1,y1,z1 = coords of the second selection (intended to be an outmost point for the sphere)
ishollow = boolean value indicating if the sphere should be hollow
The result must draw, the best it can, a perfect sphere. Here is an example:
3D space is 100x100x100
point 50,50,50 is selected first (i.e. x0 = 50; y0 = 50, z0 = 50)
point 76,67,84 is selected second (i.e. x1 = 76; y1 = 67, z1 = 84)
sphere is drawn with first point as center and second point as the greatest distance of any point in the sphere from the center
sphere must be made up of points plotted with function markpointt(x,y,z,hollowmark)
sphere must be hollow if ishollow = true. to make it hollow i need to specify if hollowmark is true, if so the point still needs to be placed but it overrides any existing points with a black point
I was unsure of where to start, can you point me in the direction to identify the mathimatical functions to code such a process? Thank you for your assistance in advance.
| 0
| 0
| 0
| 0
| 1
| 0
|
Big oh notation says that all g(n) are an element c.f(n), O(g(n)) for some constant c.
I have always wondered and never really understood why we need this arbitrary constant to multiply with the bounding function f(n) to get our bounds?
Also how does one decide what number this constant should be?
| 0
| 0
| 0
| 0
| 1
| 0
|
In order to specify some things first: The user should be able to create a graph by specifying 3 to 5 points on a 2D field.
The first and the last points are always at the bounds of that field (their position may only be changed in y direction - not x). The derivation of the graph at these positions should be 0.
The position of the 3rd and following points may be specified freely.
A graph should be interpolated, which goes through all the points. However, this graph should be as smooth and flat as possible. (please apologize for not being mathematically correct)
The important thing: I need to sample values of that graph afterwards and apply them to a discrete signal. Second thing: Within the range of the x-Axis the values of the function should not exceed the boundaries on the y-Axis.. In my pics that would be 0 and 1 on the y-Axis.
I created some pics to illustrate what I am talking about using 3 points.
Some thoughts I had:
Use (cubic?) splines: their characteristics could be applied to form such curves without too many problems. However, as far as I know, they don't relate to a global x-Axis. They are specified in relation to the next point, through a parameter usually called (s). Therefore it will be difficult to sample the values of the graph related to the x-Axis. Please correct me when I am wrong.
create a matrix, which contains the points and the derivations at those points and solve that matrix using LU decomposition or something equivalent.
So far, I don't have in depth understanding of these techniques, so I might miss some great technique or algorithm I haven't known about yet.
There is one more thing, that would be great to be able to do: Being able to adjust the steepness of the curve via the change of one or a few parameters. I illustrated this by using a red and a black graph in some of my pictures.
Any ideas or hints how to solve that efficiently?
| 0
| 0
| 0
| 0
| 1
| 0
|
Why does this code return the sum of factors of a number?
In several Project Euler problems, you are asked to compute the sum of factors as a part of the problem. On one of the forums there, someone posted the following Java code as the best way of finding that sum, since you don't actually have to find the individual factors, just the prime ones (you don't need to know Java, you can skip to my summary below):
public int sumOfDivisors(int n)
{
int prod=1;
for(int k=2;k*k<=n;k++){
int p=1;
while(n%k==0){
p=p*k+1;
n/=k;
}
prod*=p;
}
if(n>1)
prod*=1+n;
return prod;
}
Now, I've tried it many times and I see that it works. The question is, why?
Say you factor 100: 1,2,4,5,10,20,25,50,100. The sum is 217. The prime factorization is 2*2*5*5. This function gives you [5*(5+1)+1]*[2*(2+1)+1] = [25+5+1]*[4+2+1] = 217
Factoring 8: 1,2,4,8. The sum is 15. The prime factorization is 2*2*2. This function gives you [2*(2*(2+1)+1)+1]=15
The algorithm boils down to (using Fi to mean the ith index of the factor F or F sub i):
return product(sum(Fi^k, k from 0 to Ni), i from 1 to m)
where m is number of unique prime factors, Ni is the number of times each unique factor occurs in the prime factorization.
Why is this formula equal to the sum of the factors? My guess is that it equals the sum of every unique combination of prime factors (i.e. every unique factor) via the distributive property, but I don't see how.
| 0
| 0
| 0
| 0
| 1
| 0
|
I wish to plot an ellipse by scanline finding the values for y for each value of x.
For a plain ellipse the formula is trivial to find: y = Sqrt[b^2 - (b^2 x^2)/a^2]
But when the axes of the ellipse are rotated I've never been able to figure out how to compute y (and possibly the extents of x)
| 0
| 0
| 0
| 0
| 1
| 0
|
Possible Duplicate:
Why does .NET use banker's rounding as default?
Here is a sample code
decimal num1=390, num2=60, result;
result=num1/num2; // here I get 6.5
result=Math.Round(result,0);
the final value of result should be 7 but, I am getting 6. Why such a behavior?
| 0
| 0
| 0
| 0
| 1
| 0
|
Given a clocked 3-level (-1,0,+1) channel between two devices, what is the most stream-efficient way to convert a stream of bits to and from the channel representation?
The current method is to take 3 binary bits, and convert into two trits. I believe this wastes 11% of the channel capability (since 1 out of 9 possible pairs is never used). I suspect grouping might reduce this waste, but this project is using 8-bit devices, so my group sizes are restricted.
I'd like to use divmod-3, but I don't have the entire binary stream available at any one point. Is there a method for an 'incremental' divmod3 that can start at the LSB?
As an untrained guess, I speculate that there should be an approach of the form 'analyze the next 3 bits, remove one bit, change one bit' -- but I haven't been able to find something workable.
| 0
| 0
| 0
| 0
| 1
| 0
|
i'm having the following code where i check onload what the original size of an image is:
$(".post-body img").each(function() {
$(this).data('width', $(this).width());
$(this).data('height', $(this).height());
});
after that i'm resizing all images to the width of the parent div .post-body.
var bw = $('.post-body').width();
$(".post-body img").each(function() {
// Check the width of the original image size
if (bw < $(this).data('width')) {
$(this).removeAttr('height');
$(this).attr( 'width', bw );
//$(this).attr( 'height', height-in-ratio );
}
});
this works just fine! so i'm checking if the .post-body width is smaller than the original width of the image i'm resizing the image to the same width as the div.
however i think this is kind of buggy in some older versions of Internet Explorer because i'm removing the height-attribute of the image.
what is the easiest way to calculate the proportional height of an image if the old width and height is stored? i have a new width and i want to calculate the appropriate height.
i cannot seem to find an easy mathematical solution.
So again, i don't want to remove the height attribute from the image, but calculate the proportional height.
thank you for the tipp.
regards
| 0
| 0
| 0
| 0
| 1
| 0
|
I am slightly confused as to what "feature selection / extractor / weights" mean and the difference between them. As I read the literature sometimes I feel lost as I find the term used quite loosely, my primary concerns are --
When people talk of Feature Frequency, Feature Presence - is it feature selection?
When people talk of algorithms such as Information Gain, Maximum Entropy - is it still feature selection.
If I train the classifier - with a feature set that asks the classifier to note the position of a word within a document as an example - would one still call this feature selection?
Thanks
Rahul Dighe
| 0
| 1
| 0
| 0
| 0
| 0
|
if I have 2 lists of time intervals :
List1 :
1. 2010-06-06 to 2010-12-12
2. 2010-05-04 to 2010-11-02
3. 2010-02-04 to 2010-10-08
4. 2010-04-01 to 2010-08-02
5. 2010-01-03 to 2010-02-02
and
List2 :
1. 2010-06-08 to 2010-12-14
2. 2010-04-04 to 2010-10-10
3. 2010-02-02 to 2010-12-16
What would be the best way to calculate some sort of correlation or similarity factor between the two lists?
Thanks!
| 0
| 0
| 0
| 0
| 1
| 0
|
Dividing an int by zero, will throw an exception, but a float won't - at least in Java. Why does a float have additional NaN info, while an int type doesn't?
| 0
| 0
| 0
| 0
| 1
| 0
|
I want to visually join two circles that are overlapping so that
becomes
I already have methods for partial circles, but now I need to know how large the overlapping angle for earch circle is, and I don't know how to do that.
Anyone got an Idea?
| 0
| 0
| 0
| 0
| 1
| 0
|
There is a calculator program that I have came across on Windows long ago. I couldn't recall its name, but one impressive thing about it is that it can calculate numbers up to 512 bytes size. Requesting a pi value, for instance, it can give out numbers with hundreds of digits. (but of course it takes a few seconds to output) Normally, an int would be 4 bytes, double 8 bytes, etc.
Now, how can we do that? How can we allocate a variable for numbers that can exceed the normal range? (as in, int is 4 bytes, long is 8 bytes) And how to prevent overflow and underflow in this case? Assume that this is C++.
| 0
| 0
| 0
| 0
| 1
| 0
|
What would be the complexity of converting a string to its equivalent number or vice versa? Does it change depending on programming language?
On the face of it, one needs to traverse the entire string to convert it to a number, so it is O(n), or is some typecasting used?
This doubt came about when I was writing a routine to check if a given number is a palindrome or not. One approach would be to keep dividing the number by the base (here 10), accumulate digits, and put them together at the end. Example: 309/10=rem(9), 30/10=rem(0), 3/10=rem(3). we get 903.
Another approach I took was to convert this number into a string, and since strings have loads of member functions to split, reverse etc., the code was a lot shorter and cleaner, but is this the best way to do this?
| 0
| 0
| 0
| 0
| 1
| 0
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.