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
|
|---|---|---|---|---|---|---|
Hopefully the last NN question you'll get from me this weekend, but here goes :)
Is there a way to handle an input that you "don't always know"... so it doesn't affect the weightings somehow?
Soo... if I ask someone if they are male or female and they would not like to answer, is there a way to disregard this input? Perhaps by placing it squarely in the centre? (assuming 1,0 inputs at 0.5?)
Thanks
| 0
| 0
| 0
| 1
| 0
| 0
|
If a game map is partitioned into subgraphs, how to minimize edges between subgraphs?
I have a problem, Im trying to make A* searches through a grid based game like pacman or sokoban, but i need to find "enclosures". What do i mean by enclosures? subgraphs with as few cut edges as possible given a maximum size and minimum size for number of vertices for each subgraph that act as a soft constraints.
Alternatively you could say i am looking to find bridges between subgraphs, but its generally the same problem.
Example
Gridbased gamemap example http://dl.dropbox.com/u/1029671/map1.jpg
Given a game that looks like this, what i want to do is find enclosures so that i can properly find entrances to them and thus get a good heuristic for reaching vertices inside these enclosures.
alt text http://dl.dropbox.com/u/1029671/map.jpg
So what i want is to find these colored regions on any given map.
My Motivation
The reason for me bothering to do this and not just staying content with the performance of a simple manhattan distance heuristic is that an enclosure heuristic can give more optimal results and i would not have to actually do the A* to get some proper distance calculations and also for later adding competitive blocking of opponents within these enclosures when playing sokoban type games. Also the enclosure heuristic can be used for a minimax approach to finding goal vertices more properly.
Possible solution
A possible solution to the problem is the Kernighan Lin algorithm :
function Kernighan-Lin(G(V,E)):
determine a balanced initial partition of the nodes into sets A and B
do
A1 := A; B1 := B
compute D values for all a in A1 and b in B1
for (i := 1 to |V|/2)
find a[i] from A1 and b[i] from B1, such that g[i] = D[a[i]] + D[b[i]] - 2*c[a][b] is maximal
move a[i] to B1 and b[i] to A1
remove a[i] and b[i] from further consideration in this pass
update D values for the elements of A1 = A1 / a[i] and B1 = B1 / b[i]
end for
find k which maximizes g_max, the sum of g[1],...,g[k]
if (g_max > 0) then
Exchange a[1],a[2],...,a[k] with b[1],b[2],...,b[k]
until (g_max <= 0)
return G(V,E)
My problem with this algorithm is its runtime at O(n^2 * lg(n)), i am thinking of limiting the nodes in A1 and B1 to the border of each subgraph to reduce the amount of work done.
I also dont understand the c[a][b] cost in the algorithm, if a and b do not have an edge between them is the cost assumed to be 0 or infinity, or should i create an edge based on some heuristic.
Do you know what c[a][b] is supposed to be when there is no edge between a and b?
Do you think my problem is suitable to use a multi level method? Why or why not?
Do you have a good idea for how to reduce the work done with the kernighan-lin algorithm for my problem?
| 0
| 1
| 0
| 0
| 0
| 0
|
I have a text file containing posts in English/Italian. I would like to read the posts into a data matrix so that each row represents a post and each column a word. The cells in the matrix are the counts of how many times each word appears in the post. The dictionary should consist of all the words in the whole file or a non exhaustive English/Italian dictionary.
I know this is a common essential preprocessing step for NLP. And I know it's pretty trivial to code it, sill I'd like to use some NLP domain specific tool so I get stop-words trimmed etc..
Does anyone know of a tool\project that can perform this task?
Someone mentioned apache lucene, do you know if lucene index can be serialized to a data-structure similar to my needs?
| 0
| 1
| 0
| 0
| 0
| 0
|
I have this loop that runs in O(end - start) and I would like to replace it with something O(1).
If "width" wouldn't be decreasing, it would be pretty simple.
for (int i = start; i <= end; i++, width--)
if (i % 3 > 0) // 1 or 2, but not 0
z += width;
start, end and width have positive values
| 0
| 0
| 0
| 0
| 1
| 0
|
What does the following function perform?
public static double CleanAngle(double angle) {
while (angle < 0)
angle += 2 * System.Math.PI;
while (angle > 2 * System.Math.PI)
angle -= 2 * System.Math.PI;
return angle;
}
This is how it is used with ATan2. I believe the actually values passed to ATan2 are always positive.
static void Main(string[] args) {
int q = 1;
//'x- and y-coordinates will always be positive values
//'therefore, do i need to "clean"?
foreach (Point oPoint in new Point[] { new Point(8,20), new Point(-8,20), new Point(8,-20), new Point(-8,-20)}) {
Debug.WriteLine(Math.Atan2(oPoint.Y, oPoint.X), "unclean " + q.ToString());
Debug.WriteLine(CleanAngle(Math.Atan2(oPoint.Y, oPoint.X)), "cleaned " + q.ToString());
q++;
}
//'output
//'unclean 1: 1.19028994968253
//'cleaned 1: 1.19028994968253
//'unclean 2: 1.95130270390726
//'cleaned 2: 1.95130270390726
//'unclean 3: -1.19028994968253
//'cleaned 3: 5.09289535749705
//'unclean 4: -1.95130270390726
//'cleaned 4: 4.33188260327232
}
UPDATE
Thank you all for your answers. For every answer there is another question.
Why would they be "normalizing" the angle? Here is the a portion of the code.
double _theta = Math.ATan2(oEnd.Y - _start.Y, oEnd.X - _start.X);
Point oCenter = new Point();
oCenter.X = (int)(_start.X + _distanceTravelled * Math.Cos(_theta));
oCenter.Y = (int)(_start.Y + _distanceTravelled * Math.Sin(_theta));
//'move barrage
this.Left = oCenter.X - this.Width / 2;
this.Top = oCenter.Y - this.Height / 2;
| 0
| 0
| 0
| 0
| 1
| 0
|
I'm using CML to manage the 3D math in an OpenGL-based interface project I'm making for work. I need to know the width of the viewing frustum at a given distance from the eye point, which is kept as a part of a 4x4 matrix that represents the camera. My goal is to position gui objects along the apparent edge of the viewport, but at some distance into the screen from the near clipping plane.
CML has a function to extract the planes of the frustum, giving them back in Ax + By + Cz + D = 0 form. This frustum is perpendicular to the camera, which isn't necessarily aligned with the z axis of the perspective projection.
I'd like to extract x and z coordinates so as to pin graphical elements to the sides of the screen at different distances from the camera. What is the best way to go about doing it?
Thanks!
| 0
| 0
| 0
| 0
| 1
| 0
|
i'm working on a project and i have a subset of user's key-stroke time data.This means that the user makes n attempts and i will use these recorded attempt time data in various kinds of classification algorithms for future user attempts to verify that the login process is done by the user or some another person. (Simply i can say that this is biometrics)
I have 3 different times of the user login attempt process, ofcourse this is subset of the infinite data.
until now it is an easy classification problem, i decided to use WEKA but as far as i understand i have to create some fake data to feed the classification algorithm.The user's measured attempts will be 1 and fake data will be 0.
can i use some optimization algorithms ? or is there any way to create this fake data to get min false positives ?
Thanks
| 0
| 0
| 0
| 1
| 0
| 0
|
I'm trying to design an implementation of Vector Quantization as a c++ template class that can handle different types and dimensions of vectors (e.g. 16 dimension vectors of bytes, or 4d vectors of doubles, etc).
I've been reading up on the algorithms, and I understand most of it:
here and here
I want to implement the Linde-Buzo-Gray (LBG) Algorithm, but I'm having difficulty figuring out the general algorithm for partitioning the clusters. I think I need to define a plane (hyperplane?) that splits the vectors in a cluster so there is an equal number on each side of the plane.
[edit to add more info]
This is an iterative process, but I think I start by finding the centroid of all the vectors, then use that centroid to define the splitting plane, get the centroid of each of the sides of the plane, continuing until I have the number of clusters needed for the VQ algorithm (iterating to optimize for less distortion along the way). The animation in the first link above shows it nicely.
My questions are:
What is an algorithm to find the plane once I have the centroid?
How can I test a vector to see if it is on either side of that plane?
| 0
| 0
| 0
| 0
| 1
| 0
|
Say I have a base form of a word and a tag from the Penn Treebank Tag Set. How can I get the conjugated form? For example for "do" and "VBN" how can I get "done"?
I thinks this task is already implemented in some nlp library, so I'd rather not invent the bicycle. Does something like that exist?
| 0
| 1
| 0
| 0
| 0
| 0
|
I decided to learn concurrency and wanted to find out in how many ways instructions from two different processes could overlap. The code for both processes is just a 10 iteration loop with 3 instructions performed in each iteration. I figured out the problem consisted of leaving X instructions fixed at a point and then fit the other X instructions from the other process between the spaces taking into account that they must be ordered (instruction 4 of process B must always come before instruction 20).
I wrote a program to count this number, looking at the results I found out that the solution is n Combination k, where k is the number of instructions executed throughout the whole loop of one process, so for 10 iterations it would be 30, and n is k*2 (2 processes). In other words, n number of objects with n/2 fixed and having to fit n/2 among the spaces without the latter n/2 losing their order.
Ok problem solved. No, not really. I have no idea why this is, I understand that the definition of a combination is, in how many ways can you take k elements from a group of n such that all the groups are different but the order in which you take the elements doesn't matter. In this case we have n elements and we are actually taking them all, because all the instructions are executed ( n C n).
If one explains it by saying that there are 2k blue (A) and red (B) objects in a bag and you take k objects from the bag, you are still only taking k instructions when 2k instructions are actually executed. Can you please shed some light into this?
Thanks in advance.
| 0
| 0
| 0
| 0
| 1
| 0
|
I have an interesting problem here I've been trying to solve for the last little while:
I have 3 circles on a 2D xy plane, each with the same known radius. I know the coordinates of each of the three centers (they are arbitrary and can be anywhere).
What is the largest triangle that can be drawn such that each vertex of the triangle sits on a separate circle, what are the coordinates of those verticies?
I've been looking at this problem for hours and asked a bunch of people but so far only one person has been able to suggest a plausible solution (though I have no way of proving it).
The solution that we have come up with involves first creating a triangle about the three circle centers. Next we look at each circle individually and calculate the equation of a line that passes through the circle's center and is perpendicular to the opposite edge. We then calculate two intersection points of the circle. This is then done for the next two circles with a result of 6 points. We iterate over the 8 possible 3 point triangles that these 6 points create (the restriction is that each point of the big triangle must be on a separate circle) and find the maximum size.
The results look reasonable (at least when drawn out on paper) and it passes the special case of when the centers of the circles all fall on a straight line (gives a known largest triangle). Unfortunate i have no way of proving this is correct or not.
I'm wondering if anyone has encountered a problem similar to this and if so, how did you solve it?
Note: I understand that this is mostly a math question and not programming, however it is going to be implemented in code and it must be optimized to run very fast and efficient. In fact, I already have the above solution in code and tested to be working, if you would like to take a look, please let me know, i chose not to post it because its all in vector form and pretty much impossible to figure out exactly what is going on (because it's been condensed to be more efficient).
Lastly, yes this is for school work, though it is NOT a homework question/assignment/project. It's part of my graduate thesis (abet a very very small part, but still technically is part of it).
Thanks for your help.
Edit: Heres a new algorithm that i came up with a little while ago.
Starting at a circle's centre, draw a line to the other two centres. Calculate the line that bisects the angle created and calculate the intersections between the circle and the line that passes through the centre of your circle. You will get 2 results. Repeat this for the other two circles to get a total of 6 points. Iterate over these 6 points and get 8 possible solutions. Find the maximum of the 8 solutions.
This algorithm will deal with the collinear case if you draw your lines in one "direction" about the three points.
From the few random trials i have attempted using CAD software to figure out the geometries for me, this method seems to outperform all other methods previously stated However, it has already been proven to not be an optimal solution by one of Victor's counter examples.
I'll code this up tomorrow, for some reason I've lost remote access to my university computer and most things are on it.
| 0
| 0
| 0
| 0
| 1
| 0
|
In a follow-up to this answer I want to ask if any of you know any good (and more importantly easy to understand) tutorials and / or examples of data mining with the Weka toolkit.
I've been very interested in Data Mining ever since I've first heard of it and the things it can do, I've also have some experiments I'd like to do with some of my data and I've already bought four books and I found specially interesting the following two:
Data Mining http://ecx.images-amazon.com/images/I/61DhYb1Z6QL._BO2,204,203,200_PIsitb-sticker-arrow-click,TopRight,35,-76_AA240_SH20_OU01_.jpg
The last one is written by the same authors of Weka and contains a lot of examples but still, I found it a little hard to understand the logic and specially the math. My math skills are currently very rough, I plan to go to the University this year and hopefully I'll learn and be able to better understand the math involved, but until then I want to gain some practice in Data Mining.
Is there any step-by-step tutorial with example data I can read to get me started with the Weka toolkit?
| 0
| 0
| 0
| 1
| 0
| 0
|
I want to do a riddle AI chatbot for my AI class.
So i figgured the input to the chatbot would be :
Something like :
"It is blue, and it is up, but it is not the ceiling"
Translation :
<Object X>
<blue>
<up>
<!ceiling>
</Object X>
(Answer : sky?)
So Input is a set of characteristics (existing \ not existing in the object), output is a matched, most likely object.
The domain will be limited to a number of objects, i could input all attributes myself, but i was thinking :
How could I programatically build a database of characteristics for a word?
Is there such a database available? How could i tag a word, how could i programatically find all it's attributes? I was thinking on crawling wikipedia, or some forum, but i can't see it build any reliable word tag database.
Any ideas on how i could achieve such a thing? Any ideas on some literature on the subject?
Thank you
| 0
| 1
| 0
| 0
| 0
| 0
|
When using the usual formulas to calculate intersection between two 2D segments, ie here, if you round the result to an integer, you get non-symmetric results.
That is, sometimes, due to rounding errors, I get that intersection(A,B)!=intersection(B,A).
The best solution is to keep working with floats, and compare the results up to a certain precision. However, I must round the results to integers after calculating the intersection, I cannot keep working with floats.
My best solution so far was to use some full order on the segments in the plane, and have intersection to always compare the smaller segment to the larger segment.
Is there a better method? Am I missing something?
| 0
| 0
| 0
| 0
| 1
| 0
|
What is the most efficient way to solve system of equations involving the digamma function?
I have a vector v and I want to solve for a vector w such that for all i:
digamma(sum(w)) - digamma(w_i) = v_i
and
w_i > 0
I found the gsl function gsl_sf_psi, which is the digamma function (calculated using some kind of series.) Is there an identity I can use to reduce the equations? Is my best bet to use a solver? I am using C++0x; which solver is easiest to use and fast?
From my preliminary research, digamma is not easily invertible (searching for inverse digamma gives algorithms that work by binary search), so it makes sense that there would be no simplification to the whole system.
So, using a solver now leaves two problems: dealing with the fact that digamma is very slow to calculate, and dealing with the restriction that w_i > 0, or else digamma(w_i) will crash for w_i = 0.
For the first problem, I thought maybe I should implement a cache for recently calculated values of digamma -- I thought that would be a good idea, but don't know much about how root-finding algorithms work.
My idea was to solve the second problem was to find w'_i = log(w_i). That way, w'_i are on the whole line. I wonder if this is a good idea. There's probably no function to find digamma(exp(w')) directly? Also, the algorithm might take steps in w' space and not improve things because the mapping from w'->w loses some precision and so two elements of w' might map to the same w.
There's still the question of finding a good, fast rootfinding algorithm. I think I may ask that in a separate question.
Thanks...
| 0
| 0
| 0
| 0
| 1
| 0
|
In Australia we have to advertise products with tax already added, so rather than say a product is $10 + $1 GST = $11, we normally work backwards and say "ok, total is $10, how much of that is GST ?"
For example, for a $10 total, you do 10 * (1 /11) = 0.91, which is the tax component of the $10 total. My problem is I need calculate a formula for working out the taxable component when the tax rate is a variable. So far I've made this calculation although I'm not sure how correct an assertion it is:
10 * (1 / x) = 0.09 * (1 / y)
where y = 10, x = 11
Basically i want to work out x on the left hand side when I know that the tax rate is 0.05 for example, which will give me a formula that I can use to calculate the taxable component of an total figure. I want a function into which I can plug in the total price and the tax rate, and get back the taxable component of the total price.
I'd really appreciate the help with this as it really makes my head hurt ! :")
| 0
| 0
| 0
| 0
| 1
| 0
|
I'm currently involved in a project where I have very large image volumes. This volumes have to processed very fast (adding, subtracting, thresholding, and so on). Additionally most of the volume are so large that they event don't fit into the memory of the system.
For that reason I have created an abstract volume class (VoxelVolume) that host the volume and image data and overloads the operators so that it's possible to perform the regular mathematical operations on volumes. Thereby two more questions opened up which I will put into stackoverflow into two additional threads.
Here is my first question. My volume is implemented in a way that it only can contain float array data, but most of the containing data is from an UInt16 image source. Only operations on the volume can create float array images.
When I started implementing such a volume the class looked like following:
public abstract class VoxelVolume<T>
{
...
}
but then I realized that overloading the operators or return values would get more complicated. An example would be:
public abstract class VoxelVolume<T>
{
...
public static VoxelVolume<T> Import<T>(param string[] files)
{
}
}
also adding two overloading operators would be more complicated:
...
public static VoxelVolume<T> operator+(VoxelVolume<T> A, VoxelVolume<T> B)
{
...
}
Let's assume I can overcome the problems described above, nevertheless I have different types of arrays that contain the image data. Since I have fixed my type in the volumes to float the is no problem and I can do an unsafe operation when adding the contents of two image volume arrays. I have read a few threads here and had a look around the web, but found no real good explanation of what to do when I want to add two arrays of different types in a fast way. Unfortunately every math operation on generics is not possible, since C# is not able to calculate the size of the underlying data type. Of course there might by a way around this problem by using C++/CLR, but currently everything I have done so far, runs in 32bit and 64bit without having to do a thing. Switching to C++/CLR seemed to me (pleased correct me if I'm wrong) that I'm bound to a certain platform (32bit) and I have to compile two assemblies when I let the application run on another platform (64bit). Is this true?
So asked shortly: How is it possible to add two arrays of two different types in a fast way. Is it true that the developers of C# haven't thought about this. Switching to a different language (C# -> C++) seems not to be an option.
I realize that simply performing this operation
float []A = new float[]{1,2,3};
byte []B = new byte[]{1,2,3};
float []C = A+B;
is not possible and unnecessary although it would be nice if it would work. My solution I was trying was following:
public static class ArrayExt
{
public static unsafe TResult[] Add<T1, T2, TResult>(T1 []A, T2 []B)
{
// Assume the length of both arrays is equal
TResult[] result = new TResult[A.Length];
GCHandle h1 = GCHandle.Alloc (A, Pinned);
GCHandle h2 = GCHandle.Alloc (B, Pinned);
GCHandle hR = GCHandle.Alloc (C, Pinned);
void *ptrA = h1.ToPointer();
void *ptrB = h2.ToPointer();
void *ptrR = hR.ToPointer();
for (int i=0; i<A.Length; i++)
{
*((TResult *)ptrR) = (TResult *)((T1)*ptrA + (T2)*ptrB));
}
h1.Free();
h2.Free();
hR.Free();
return result;
}
}
Please excuse if the code above is not quite correct, I wrote it without using an C# editor. Is such a solution a shown above thinkable? Please feel free to ask if I made a mistake or described some things incompletely.
Thanks for your help
Martin
| 0
| 0
| 0
| 0
| 1
| 0
|
I have very little programming knowledge; only a fair bit in Visual Basic.
How do I take a value from a text field, then do some simple math such as divide the value by two, then display it back to the user in the same field?
In Visual Basic you could just do txtBoxOne.text = txtBoxOne.text / 2
I understand this question is more than one question and is very basic stuff, but I need to get my head out of Visual Basic and into where I should be :)
| 0
| 0
| 0
| 0
| 1
| 0
|
Given curves of type Circle and Circular-Arc in 3D space, what is a good way to compute accurate bounding boxes (world axis aligned)?
Edit: found solution for circles, still need help with Arcs.
C# snippet for solving BoundingBoxes for Circles:
public static BoundingBox CircleBBox(Circle circle)
{
Point3d O = circle.Center;
Vector3d N = circle.Normal;
double ax = Angle(N, new Vector3d(1,0,0));
double ay = Angle(N, new Vector3d(0,1,0));
double az = Angle(N, new Vector3d(0,0,1));
Vector3d R = new Vector3d(Math.Sin(ax), Math.Sin(ay), Math.Sin(az));
R *= circle.Radius;
return new BoundingBox(O - R, O + R);
}
private static double Angle(Vector3d A, Vector3d B)
{
double dP = A * B;
if (dP <= -1.0) { return Math.PI; }
if (dP >= +1.0) { return 0.0; }
return Math.Acos(dP);
}
| 0
| 0
| 0
| 0
| 1
| 0
|
I'm looking for a Java library to help parse user entered text that represents an 'appointment' for a calendar application. For instance:
Lunch with Mike at 11:30 on Tuesday
or
5pm Happy hour on Friday
I've found some promising leads like https://github.com/samtingleff/jchronic and http://www.datejs.com/ which can parse dates - but I also need to be able to extract the title of the event like "Lunch with Mike".
If such an API doesn't exist, I'm also interested in any thoughts on how best to approach the problem from a coding perspective.
| 0
| 1
| 0
| 0
| 0
| 0
|
I'm working on a C# program that deals with Oracle Spatial geometry. When circle data is stored in a geometry field only three non-collinear points are stored to represent the circle. The problem is that I need to use this data on a Google Maps web page and need the center point and radius of the circle (since my circle drawing function uses that information).
Can anyone help with the math involved and translating said math to C#? I think this page may hold the answer, but I'm having a hard time following it. There are formulas for radius and center given three points, but then they define the variables as matrices and I get lost at that point. How would I solve that in code?
| 0
| 0
| 0
| 0
| 1
| 0
|
I'm in a strange situation where I have a value of 0.5 and I want to convert the values from 0.5 to 1 to be a percentage and from 0.5 to 0 to be a negative percentage.
As it says in the title 0.4 should be -20%, 0.3 should be -40% and 0.1 should be -80%.
I'm sure this is a simple problem, but my mind is just refusing to figure it out :)
Can anyone help? :)
| 0
| 0
| 0
| 0
| 1
| 0
|
In my graduate class on compiler construction we've been introduced to the concept of a lattice. Three lectures have been devoted to lattices and so far it seems like an interesting tangent, but the dilemma is that it doesn't really help explain how a compiler uses a lattice to solve a concrete problem.
We have already covered parsing and typechecking. We're about to start liveness analysis and register allocation.
Note, I'm not looking for resources on building compilers. The following list of links have that covered pretty well. What I'm looking for is an explanation on the relationship between compilers and lattices, bonus points for the most examples.
Learning Resources on Parsers, Interpreters, and Compilers
How much of the compiler should we know?
Learning to write a compiler
| 0
| 0
| 0
| 0
| 1
| 0
|
I want to create an object, let's say a Pie.
class Pie
def initialize(name, flavor)
@name = name
@flavor = flavor
end
end
But a Pie can be divided in 8 pieces, a half or just a whole Pie. For the sake of argument, I would like to know how I could give each Pie object a price per 1/8, 1/4 or per whole. I could do this by doing:
class Pie
def initialize(name, flavor, price_all, price_half, price_piece)
@name = name
@flavor = flavor
@price_all = price_all
@price_half = price_half
@price_piece = price_piece
end
end
But now, if I would create fifteen Pie objects, and I would take out randomly some pieces somewhere by using a method such as
getPieceOfPie(pie_name)
How would I be able to generate the value of all the available pies that are whole and the remaining pieces? Eventually using a method such as:
myCurrentInventoryHas(pie_name)
# output: 2 whole strawberry pies and 7 pieces.
I know, I am a Ruby nuby. Thank you for your answers, comments and help!
| 0
| 0
| 0
| 0
| 1
| 0
|
Knowing that we can use Divide-and-Conquer algorithm to compute large exponents, for example 2 exp 100 = 2 exp(50) * 2 exp(50), which is quite more efficient, is this method efficient using roots? For example 2 exp (1/100) = (2 exp(1/50)) exp(1/50)?
In other words, I'm wondering if (n exp(1/x)) is more efficient to (n exp(1/y)) for x < y and where x and y are integers.
| 0
| 0
| 0
| 0
| 1
| 0
|
I have a decimal number (let's call it goal) and an array of other decimal numbers (let's call the array elements) and I need to find all the combinations of numbers from elements which sum to goal.
I have a preference for a solution in C# (.Net 2.0) but may the best algorithm win irrespective.
Your method signature might look something like:
public decimal[][] Solve(decimal goal, decimal[] elements)
| 0
| 0
| 0
| 0
| 1
| 0
|
I'm trying to determine the function for determining the number of unordered combinations with non-unique choices.
Given:
n = number of unique symbols to select from
r = number of choices
Example... for n=3, r=3, the result would be: (edit: added missing values pointed out by Dav)
000
001
002
011
012
022
111
112
122
222
I know the formula for permutations (unordered, unique selections), but I can't figure out how allowing repetition increases the set.
| 0
| 0
| 0
| 0
| 1
| 0
|
Is there any tricky way to implement a set data structure (a collection of unique values) in C? All elements in a set will be of the same type and there is a huge RAM memory.
As I know, for integers it can be done really fast'N'easy using value-indexed arrays. But I'd like to have a very general Set data type. And it would be nice if a set could include itself.
| 0
| 0
| 0
| 0
| 1
| 0
|
If P( cj | xi ) are already known, where i=1,2,...n; j=1,2,...k;
How do I calculate/estimate:
P( cj | xl , xm , xn ), where j=1,2,...k; l,m,n belongs to http://latex.mathoverflow.net/jsMath/fonts/cmsy10/alpha/120/char32.png {1,2,...n} ?
| 0
| 1
| 0
| 0
| 0
| 0
|
I have a basic question about Bayesian networks.
Let's assume we have an engine, that with
1/3 probability can stop working.
I'll call this variable ENGINE.
If it stops working, then your car
doesn't work. If the engine is
working, then your car will work 99%
of the time. I'll call this one CAR.
Now, if your car is old(OLD),
instead of not working 1/3 of the
time, your engine will stop working
1/2 of the time.
I'm being asked to first design the network and then assign all the conditional probabilities associated with the table.
I'd say the diagram of this network would be something like
OLD -> ENGINE -> CAR
Now, for the conditional probabilities tables I did the following:
OLD |ENGINE
------------
True | 0.50
False | 0.33
and
ENGINE|CAR
------------
True | 0.99
False | 0.00
Now, I am having trouble about how to define the probabilities of OLD. In my point of view, old is not something that has a CAUSE relationship with ENGINE, I'd say it is more a characteristic of it. Maybe there is a different way to express this in the diagram? If the diagram is indeed correct, how would I go to make the tables?
| 0
| 1
| 0
| 0
| 0
| 0
|
We're making this web app in PHP and when working in the reports we have Excel files to compare our results to make sure our coding is doing the right operations.
Now we're running into some differences due floating point arithmetics. We're doing the same divisions and multiplications and running into slightly different numbers, that add up to a notable difference.
My question is if Excel is delegating it's floating point arithmetic to the CPU and PHP is also relying in the CPU for it's operations. Or does each application implements its own set of math algorithms?
| 0
| 0
| 0
| 0
| 1
| 0
|
I'm trying to implement thinking-sphinx across multiple 'sites' hosted under a single rails application. I'm working with the developer of thinking-sphinx to sort through the finer details and am making good progress, but I need help with a maths problem:
Usually the formula for making a unique ID in a thinking-sphinx search index is to take the id, multiply it by the total number of models that are searchable, and add the number of the currently indexed model:
id * total_models + current_model
This works well, but now I also through an entity_id into the mix, so there are three vextors for making this ID unique. Could someone help me figure out the equation to gaurantee that the id's will never collide using these three variables:
id, total_models, total_entities
The entity ID is an integer.
I thought of:
id * (total_models + total_entities) + (current_model + current_entity)
but that results in collisions.
Any help would be greatly appreciated :)
| 0
| 0
| 0
| 0
| 1
| 0
|
I am parsing binary files and have to implement a CRC algorithm to ensure the file is not corrupted. Problem is that I can't seem to get the binary math working when using larger numbers.
The example I'm trying to get working:
BigInteger G = new BigInteger("11001", 2);
BigInteger M = new BigInteger("1110010000", 2);
BigInteger R = M.remainder(G);
I am expecting:
R = "0101"
But I am getting:
R = "1100"
I am assuming the remainder of 0101 is correct since it is given to me in this book I am using as a reference for the CRC algorithm (it's not based in Java), but I can't seem to get it working. I can get small binary calculations to work that I have solved by hand, but not the larger ones. I'll admit that I haven't worked the larger ones by hand yet, that is my next step, but I wanted to see if someone could point out a glaring flaw I have in my code.
Can anyone confirm or deny that my methodology is correct?
Thanks
| 0
| 0
| 0
| 0
| 1
| 0
|
Does Actionscript have a function that would tell me what number the input is a square root of. For example:
4 //output 2, because 4 is the square root of 2
16 //output 4, because 16 is the square root of 4
| 0
| 0
| 0
| 0
| 1
| 0
|
I need an formula for determining a debt payoff plan where the following are known: number of payments, amount per payment, and principal and need to figure out what the interest rate would be from that. I am re-factoring existing code and the current method uses the following (compounded = 12;interest rate starts at .1) :
while (counter < 100)
{
intermediatePayment = (interestRate*(principal/compounded))/(1 - (1/Math.Pow(interestRate/compounded + 1,(compounded*numberOfYears))));
interestIncrement = Math.Abs(interestRate - previousRate)/2;
previousRate = interestRate;
if(intermediatePayment == payment)
break;
if (intermediatePayment > payment)
interestRate -= interestIncrement;
else
interestRate += interestIncrement;
counter++;
}
Now I understand what this formula does but I would never be able to arrive at it myself. What's here is actually an equation that is supposed to be used to determine monthly payment if interest rate,principal, and number of payments is known. It is using brute force and looping (at most 100 times) until the calculated payment equals the desired payment. It arrives at an answer usually after about 40-50 loops and that could be optimized by reducing significant digits.
Seems to me if we just solved for interestRate there would be no looping. Try as I might, I can't get the equation to solve for I, so that's my main question.
Now, if you understand the problem well enough and know financial formulas and compounding interest, you might provide me with an even better solution altogether, which would be awesome. I have done significant research myself and found tools but not the raw equation, or more often I find different formulas for determining interest related stuff but am not knowledgeable to retool them for my needs.
Basically I've spent too much time on this and my boss thinks since the loop works I need to leave it be or ask for help. Fair enough, so I am. :)
Here's a more traditional layout of the formula if that helps any: http://i.imgur.com/BCdsV.png
And for test data: if
P=45500
c=12
y=3
m=1400
then
I = .0676
Thanks for the help
| 0
| 0
| 0
| 0
| 1
| 0
|
I wrote a program in java that rolls a die and records the total number of times each value 1-6 is rolled. I rolled 6 Million times. Here's the distribution:
#of 0's: 0
#of 1's: 1000068
#of 2's: 999375
#of 3's: 999525
#of 4's: 1001486
#of 5's: 1000059
#of 6's: 999487
(0 wasn't an option.)
Is this distribution consistant with random dice rolls?
What objective statistical tests might confirm that the dice rolls are indeed random enough?
EDIT: questions have been raised over application: a game that i want to be as fair as can be reasonably achieved.
| 0
| 0
| 0
| 0
| 1
| 0
|
Does anybody have any idea about any recent work being done on optical character recognition for Indian scripts using modern Machine Learning techniques ? I know of some research being done at ISI, calcutta, but nothing new has come up in the last 3-4 years to the best of my knowledge, and OCR for Devanagari is sadly lacking!
| 0
| 0
| 0
| 1
| 0
| 0
|
I have a series of text items- raw HTML from a MySQL database. I want to find the most common phrases in these entries (not the single most common phrase, and ideally, not enforcing word-for-word matching).
My example is any review on Yelp.com, that shows 3 snippets from hundreds of reviews of a given restaurant, in the format:
"Try the hamburger" (in 44 reviews)
e.g., the "Review Highlights" section of this page:
http://www.yelp.com/biz/sushi-gen-los-angeles/
I have NLTK installed and I've played around with it a bit, but am honestly overwhelmed by the options. This seems like a rather common problem and I haven't been able to find a straightforward solution by searching here.
| 0
| 1
| 0
| 0
| 0
| 0
|
I'm writing a custom dice rolling parser (snicker if you must) in python. Basically, I want to use standard math evaluation but add the 'd' operator:
#xdy
sum = 0
for each in range(x):
sum += randInt(1, y)
return sum
So that, for example, 1d6+2d6+2d6-72+4d100 = (5)+(1+1)+(6+2)-72+(5+39+38+59) = 84
I was using regex to replace all 'd's with the sum and then using eval, but my regex fell apart when dealing with parentheses on either side. Is there a faster way to go about this than implementing my own recursive parsing? Perhaps adding an operator to eval?
Edit: I seem to have given a bad example, as the above example works with my current version. What I'm looking for is some way to evaluate, say, (5+(6d6))d(7-2*(1d4)).
By "fell apart", I just meant that my current regex expression failed.
I have been too vague about my failure, sorry for the confusion. Here's my current code:
def evalDice(roll_matchgroup):
roll_split = roll_matchgroup.group('roll').split('d')
print roll_split
roll_list = []
for die in range(int(roll_split[0])):
roll = random.randint(1,int(roll_split[1]))
roll_list.append(roll)
def EvalRoll(roll):
if not roll: return 0
rollPattern = re.compile('(?P<roll>\d*d\d+)')
roll_string = rollPattern.sub(evalDice, roll.lower())
for this, "1d6+4d100" works just fine, but "(1d6+4)d100" or even "1d6+4d(100)" fails.
| 0
| 0
| 0
| 0
| 1
| 0
|
I am trying to embed Maths Symbols and Equations in Ajax Editor.
or provide some solution to implement maths symbols and equations in my application using rich textbox or some controls/plugins.
Thank you.
| 0
| 0
| 0
| 0
| 1
| 0
|
I am using the following code to work out an inc and ext VAT price:
$('#totalexvat').text(totalprice);
var vat = totalprice / 100 * 17.5;
vat = roundNumber(vat,2);
$('#totalincvat').text(totalprice-vat);
Sometimes I get .3 or .9 instead of what I would like to be .30 or .90 because it's money, is there a way to do this?
| 0
| 0
| 0
| 0
| 1
| 0
|
For given integers N and K (1 <= N, K <= 2000000000) you have to find the number of digits of N^K.
Is there any formula or something ? Because I tried solving it by simply powering N**K but it's not working for large values and the program simply freezes because of the calculations. I am looking for some fast way maybe some math formula like I said before.
| 0
| 0
| 0
| 0
| 1
| 0
|
In our software we have a camera based on mouse movement, and a quarternion at its heart.
We want to fire projectiles from this position, which we can do, however we want to use the camera to aim. The projectile takes a vector which it will add to its position each game frame.
How do we acquire such a vector from a given camera/quaternion?
| 0
| 0
| 0
| 0
| 1
| 0
|
Today I found the following:
#include <stdio.h>
int main(){
char x = 255;
int z = ((int)x)*2;
printf("%d
", z); //prints -2
return 0;
}
So basically I'm getting an overflow because the size limit is determined by the operands on the right side of the = sign??
Why doesn't casting it to int before multiplying work?
In this case I'm using a char and int, but if I use "long" and "long long int" (c99), then I get similar behaviour. Is it generally advised against doing arithmetic with operands of different sizes?
| 0
| 0
| 0
| 0
| 1
| 0
|
As all developers do, we constantly deal with some kind of identifiers as part of our daily work. Most of the time, it's about bugs or support tickets. Our software, upon detecting a bug, creates a package that has a name formatted from a timestamp and a version number, which is a cheap way of creating reasonably unique identifiers to avoid mixing packages up. Example: "Bug Report 20101214 174856 6.4b2".
My brain just isn't that good at remembering numbers. What I would love to have is a simple way of generating alpha-numeric identifiers that are easy to remember.
It takes about 5 minutes to whip up an algorithm like the following in python, which produces halfway usable results:
import random
vowels = 'aeiuy' # 0 is confusing
consonants = 'bcdfghjklmnpqrstvwxz'
numbers = '0123456789'
random.seed()
for i in range(30):
chars = list()
chars.append(random.choice(consonants))
chars.append(random.choice(vowels))
chars.append(random.choice(consonants + numbers))
chars.append(random.choice(vowels))
chars.append(random.choice(vowels))
chars.append(random.choice(consonants))
print ''.join(chars)
The results look like this:
re1ean
meseux
le1ayl
kuteef
neluaq
tyliyd
ki5ias
This is already quite good, but I feel it is still easy to forget how they are spelled exactly, so that if you walk over to a colleagues desk and want to look one of those up, there's still potential for difficulty.
I know of algorithms that perform trigram analysis on text (say you feed them a whole book in German) and that can generate strings that look and feel like German words and are thus easier to handle generally. This requires lots of data, though, and makes it slightly less suitable for embedding in an application just for this purpose.
Do you know of any published algorithms that solve this problem?
Thanks!
Carl
| 0
| 1
| 0
| 0
| 0
| 0
|
According to "Introduction to Neural Networks with Java By Jeff Heaton", the input to the Kohonen neural network must be the values between -1 and 1.
It is possible to normalize inputs where the range is known beforehand:
For instance RGB (125, 125, 125) where the range is know as values between 0 and 255:
1. Divide by 255: (125/255) = 0.5 >> (0.5,0.5,0.5)
2. Multiply by two and subtract one: ((0.5*2)-1)=0 >> (0,0,0)
The question is how can we normalize the input where the range is unknown like our height or weight.
Also, some other papers mention that the input must be normalized to the values between 0 and 1. Which is the proper way, "-1 and 1" or "0 and 1"?
| 0
| 0
| 0
| 1
| 0
| 0
|
i have latitude and longitude of particular place and i want to calculate the distance so how can i calculate it?
| 0
| 0
| 0
| 0
| 1
| 0
|
Given the triangle with vertices (a,b,c):
c
/ \
/ \
/ \
a - - - - b
Which is then subdivided into four triangles by halving each of the edges:
c
/ \
/ \
ca / \ bc
_ _ _
/\ /\
/ \ / \
/ \ / \
a - - - - ab - - - -b
Which results in four triangles (a, ab, ca), (b, bc, ab), (c, ca, bc), (ab, bc, ca).
Now given a point p. How do I determine in which triangle p lies, given that p is within the outer triangle (a, b, c)?
Currently I intend to use ab as the origin. Check whether it is to the left of right of the line "ca - ab" using the perp of "ca - ab" and checking the sign against the dot product of "ab - a" and the perp vector and the vector "p - ab". If it is the same or the dot product is zero then it must be in (a, ab, ca)... Continue with this procedure with the other outer triangles (b, ba, ab) & (c, ca, ba). In the end if it didn't match with these it must be contained within the inner triangle (ab, bc, ca).
Is there a better way to do it?
EDIT
Here is a little more info of the intended application of the algorithm:
I'm using this as a subdivision mask to generate a fine mesh over which I intend to interpolate. Each of the triangles will be subdivided similarly up to a specified depth. I want to determine the triangle (at the maximum depth) within which the point p lies. With this I can evaluate a function at the point p using interpolation over the triangle. There is a class of triangles which is right-angled and they do comprise a significant portion, but they're much easier to work with and this algorithm isn't intended for them.
| 0
| 0
| 0
| 0
| 1
| 0
|
Mathematica has a built-in function ArgMax for functions over infinite domains, based on the standard mathematical definition.
The analog for finite domains is a handy utility function.
Given a function and a list (call it the domain of the function), return the element(s) of the list that maximize the function.
Here's an example of finite argmax in action:
Canonicalize NFL team names
And here's my implementation of it (along with argmin for good measure):
(* argmax[f, domain] returns the element of domain for which f of
that element is maximal -- breaks ties in favor of first occurrence. *)
SetAttributes[{argmax, argmin}, HoldFirst];
argmax[f_, dom_List] := Fold[If[f[#1]>=f[#2], #1, #2]&, First[dom], Rest[dom]]
argmin[f_, dom_List] := argmax[-f[#]&, dom]
First, is that the most efficient way to implement argmax?
What if you want the list of all maximal elements instead of just the first one?
Second, how about the related function posmax that, instead of returning the maximal element(s), returns the position(s) of the maximal elements?
| 0
| 0
| 0
| 0
| 1
| 0
|
I need to subtract 0.5 from number a and set the answer to number b. My code looks like it would work but I'm not sure what I'm doing wrong. The error I get Is on the subtraction line, the error says incompatible type for argument 1 of 'decimalNumberBySubtracting:'.
Heres my header: (Note: I only showed the numbers because the header is large)
NSDecimalNumber *a;
NSDecimalNumber *b;
Heres the rest: (Assume this is in an IBAction)
b = [a decimalNumberBySubtracting:0.5];
If anyone knows how to properly subtract any help would be appreciated.
| 0
| 0
| 0
| 0
| 1
| 0
|
I'm implementing a new machine learning algorithm in Java that extracts a prototype datastructure from a set of structured datasets (tree-structure). As im developing a generic library for that purpose, i kept my design independent from concrete data-representations like XML.
My problem now is that I need a way to define a data model, which is basically a ruleset describing valid trees, against which a set of trees is being matched. I thought of using BNF or a similar dialect.
Basically I need a way to iterate through the space of all valid TreeNodes defined by the ModelTree (Like a search through the search space for algorithms like A*) so that i can compare my set of concrete trees with the model. I know that I'll have to deal with infinite spaces there but first things first.
I know, it's rather tricky (and my sentences are pretty bumpy) but I would appreciate any clues.
Thanks in advance,
Stefan
| 0
| 0
| 0
| 1
| 0
| 0
|
Take a commonly used binary hash function - for example, SHA-256. As the name implies, it outputs a 256 bit value.
Let A be the set of all possible 256 bit binary values. A is extremely large, but finite.
Let B be the set of all possible binary values. B is infinite.
Let C be the set of values obtained by running SHA-256 on every member of B. Obviously this can't be done in practice, but I'm guessing we can still do mathematical analysis of it.
My Question: By necessity, C ⊆ A. But does C = A?
EDIT: As was pointed out by some answers, this is wholly dependent on the has function in question. So, if you know the answer for any particular hash function, please say so!
| 0
| 0
| 0
| 0
| 1
| 0
|
I have a weird math calculation here. I hope someone will explain.
$a = 1.85/100;
$b = 1.5/100;
$c = 1.1/100;
$d = 0.4/100;
$e = 0.4/100;
$f = 0.4/100;
$g = 0.4/100;
$h = $a + $b + $c + $d + $e + $f + $g;
echo $h*100 ."<br>";
$i = $h-$a;
$i = $i-$b;
$i = $i-$c;
$i = $i-$d;
$i = $i-$e;
$i = $i-$f;
$i = $i-$g;
echo $i;
The last $i value should be 0 but it returns 6.93889390391E-18.
| 0
| 0
| 0
| 0
| 1
| 0
|
I develop a Python-based drawing program, Whyteboard. I have tools that the user can create new shapes on the canvas, such as text/images/rectangles/circles/polygons. I also have a Select tool that allows the users to modify these shapes - for example, moving a shape's position, resizing, or editing polygon's points' positions.
I'm adding in a new feature where moving or resizing a point near the canvas edge will automatically scroll the canvas. I think it's a good idea in terms of program usability, and annoys me when other program's don't have this feature.
I've made some good progress on coding this; below is some Python code to demonstrate what I'm doing. These functions demonstrate how some shapes calculate their "edges":
def find_edges(self):
"""A line."""
self.edges = {EDGE_TOP: min(self.y, self.y2), EDGE_RIGHT: max(self.x, self.x2),
EDGE_BOTTOM: max(self.y, self.y2), EDGE_LEFT: min(self. x, self.x2)}
def find_edges(self):
"""An image"""
self.edges = {EDGE_TOP: self.y, EDGE_RIGHT: self.x + self.image.GetWidth(),
EDGE_BOTTOM: self.y + self.image.GetWidth(), EDGE_LEFT: self.x}
def find_edges(self):
"""Get the bounding rectangle for the polygon"""
xmin = min(x for x, y in self.points)
ymin = min(y for x, y in self.points)
xmax = max(x for x, y in self.points)
ymax = max(y for x, y in self.points)
self.edges = {EDGE_TOP: ymin, EDGE_RIGHT: xmax, EDGE_BOTTOM: ymax, EDGE_LEFT: xmin}
And here's the code I have so far to implement the scrolling when a shape nears the edge:
def check_canvas_scroll(self, x, y, moving=False):
"""
We check that the x/y coords are within 50px from the edge of the canvas
and scroll the canvas accordingly. If the shape is being moved, we need
to check specific edges of the shape (e.g. left/right side of rectangle)
"""
size = self.board.GetClientSizeTuple() # visible area of the canvas
if not self.board.area > size: # canvas is too small to need to scroll
return
start = self.board.GetViewStart() # user's starting "viewport"
scroll = (-1, -1) # -1 means no change
if moving:
if self.shape.edges[EDGE_RIGHT] > start[0] + size[0] - 50:
scroll = (start[0] + 5, -1)
if self.shape.edges[EDGE_BOTTOM] > start[1] + size[1] - 50:
scroll = (-1, start[1] + 5)
# snip others
else:
if x > start[0] + size[0] - 50:
scroll = (start[0] + 5, -1)
if y > start[1] + size[1] - 50:
scroll = (-1, start[1] + 5)
# snip others
self.board.Scroll(*scroll)
This code actually works pretty well. If we're moving a shape, then we need to know its edges to calculate when they're coming close to the canvas edge. If we're resizing just a single point, then we just use the x/y coords of that point to see if it's close to the edge.
The problem I'm having is a little tricky to describe - basically, if you move a shape to the left, and stop moving it, if you positioned the shape within the 50px from the canvas, then the next time you go to move the shape, the code that says "ok, is this shape close to the end?" gets triggered, and the canvas scrolls to the left, even if you're moving the shape to the right.
Can anyone think on how to stop this? I created a youtube video to demonstrate the issue. At about 0:54, I move a polygon to the left of the canvas and position it there. The next time I move it, the canvas scrolls to the left even though I'm moving it right
Another thing I'd like to add, but I'm stuck on is the scroll gaining momentum the longer a shape is scrolling? So, with a large canvas, you're not moving a shape for ages, moving 5px at a time, when you need to cover a 2000px distance. Any suggestions there?
Thanks all - sorry for the super long question!
| 0
| 0
| 0
| 0
| 1
| 0
|
We all hear that math at least helps a little bit with programming. My question though, does English or other natural language skills help with programming? I know it has to help with technical documentation, but what about actual programming? Are certain constructs in a programming language also there in natural languages? Does knowing how to write a 20 page research paper help with writing a 20k loc programming project?
| 0
| 1
| 0
| 0
| 0
| 0
|
Challenge
Here is the challenge (of my own invention, though I wouldn't be surprised if it has previously appeared elsewhere on the web).
Write a function that takes a single
argument that is a
string representation of a simple
mathematical expression and evaluates
it as a floating point value. A
"simple expression" may include any of
the following: positive or negative
decimal numbers, +, -, *, /, (, ).
Expressions use (normal) infix notation.
Operators should be evaluated in the
order they appear, i.e. not as in
BODMAS,
though brackets should be correctly
observed, of course. The function should return
the correct result for any possible expression
of this form. However, the function does not have
to handle malformed expressions (i.e. ones with bad syntax).
Examples of expressions:
1 + 3 / -8 = -0.5 (No BODMAS)
2*3*4*5+99 = 219
4 * (9 - 4) / (2 * 6 - 2) + 8 = 10
1 + ((123 * 3 - 69) / 100) = 4
2.45/8.5*9.27+(5*0.0023) = 2.68...
Rules
I anticipate some form of "cheating"/craftiness here, so please let me forewarn against it! By cheating, I refer to the use of the eval or equivalent function in dynamic languages such as JavaScript or PHP, or equally compiling and executing code on the fly. (I think my specification of "no BODMAS" has pretty much guaranteed this however.) Apart from that, there are no restrictions. I anticipate a few Regex solutions here, but it would be nice to see more than just that.
Now, I'm mainly interested in a C#/.NET solution here, but any other language would be perfectly acceptable too (in particular, F# and Python for the functional/mixed approaches). I haven't yet decided whether I'm going to accept the shortest or most ingenious solution (at least for the language) as the answer, but I would welcome any form of solution in any language, except what I've just prohibited above!
My Solution
I've now posted my C# solution here (403 chars). Update: My new solution has beaten the old one significantly at 294 chars, with the help of a bit of lovely regex! I suspected that this will get easily beaten by some of the languages out there with lighter syntax (particularly the funcional/dynamic ones), and have been proved right, but I'd be curious if someone could beat this in C# still.
Update
I've seen some very crafty solutions already. Thanks to everyone who has posted one. Although I haven't tested any of them yet, I'm going to trust people and assume they at least work with all of the given examples.
Just for the note, re-entrancy (i.e. thread-safety) is not a requirement for the function, though it is a bonus.
Format
Please post all answers in the following format for the purpose of easy comparison:
Language
Number of characters: ???
Fully obfuscated function:
(code here)
Clear/semi-obfuscated function:
(code here)
Any notes on the algorithm/clever shortcuts it takes.
| 0
| 0
| 0
| 0
| 1
| 0
|
I have been trying to solve this problem for a while, but couldn't with just integer arithmetic and bitwise operators. However, I think its possible and it should be fairly easy. What am I missing?
The problem: to get an integer value of arbitrary length (this is not relevant to the problem) with it's X least significant bits sets to 1 and the rest to 0. For example, given the number 31, I need to get an integer value which equals 0x7FFFFFFF (31 least significant bits are 1 and the rest zeros).
Of course, using a loop OR-ing a shifted 1 to an integer X times will do the job. But that's not the solution I'm looking for. It should be more in the direction of (X << Y - 1), thus using no loops.
| 0
| 0
| 0
| 0
| 1
| 0
|
Hey all. I'm computing the angle between two vectors, and sometimes Math.Acos() returns NaN when it's input is out of bounds (-1 > input && input > 1) for a cosine. What does that mean, exactly? Would someone be able to explain what's happening? Any help is appreciated!
Here's my method:
public double AngleBetween(vector b)
{
var dotProd = this.Dot(b);
var lenProd = this.Len*b.Len;
var divOperation = dotProd/lenProd;
// http://msdn.microsoft.com/en-us/library/system.math.acos.aspx
return Math.Acos(divOperation) * (180.0 / Math.PI);
}
Here's my implementation of Dot and Len:
public double Dot(vector b)
{
// x's and y's are lattitudes and longitudes (respectively)
return ( this.From.x*b.From.x + this.From.y*b.From.y);
}
public double Len{
get
{
// geo is of type SqlGeography (MS SQL 2008 Spatial Type) with an SRID of 4326
return geo.STLength().Value;
}
}
| 0
| 0
| 0
| 0
| 1
| 0
|
function(deltaTime) {
x = x * FACTOR; // FACTOR = 0.9
}
This function is called in a game loop. First assume that it's running at a constant 30 FPS, so deltaTime is always 1/30.
Now the game is changed so deltaTime isn't always 1/30 but becomes variable. How can I incorporate deltaTime in the calculation of x to keep the "effect per second" the same?
And what about
function(deltaTime) {
x += (target - x) * FACTOR; // FACTOR = 0.2
}
| 0
| 0
| 0
| 0
| 1
| 0
|
as I am learning the Ruby language, I am getting closer to actual programming. I was thinking of creating a simple card game. My question isn't Ruby oriented, but I do know want to learn how to solve this problem with a genuine OOP approach. In my card game, I want to have four players, using a standard deck with 52 cards, no jokers/wildcards. In the game, I won't use the ace as a dual card, it is always the highest card.
So, the programming problems I wonder about are the following:
How can I sort/randomize the deck of cards? There are four types, each having 13 values. Eventually there can be only unique values, so picking random values could generate duplicates.
How can I implement a simple AI? As there are tons of card games, someone would have figured this part out already, so references would be great.
I am a true Ruby nuby, and my goal here is to learn to solve problems, so pseudo code would be great, just to understand how to solve the problem programmatically. I apologize for my grammar and writing style if it's unclear, for it is not my native language.
Also, pointers to sites where such challenges are explained would be a great resource!
Thank you for your comments, answers and feedback!
| 0
| 1
| 0
| 0
| 0
| 0
|
How to prove this:
4n = O(8n)
8n = O(4n)?
So what are the C and n0 values for both cases?
| 0
| 0
| 0
| 0
| 1
| 0
|
I have a whole bunch of percentages stored as XX% (e.g. 12%, 50%, etc..) I need to remove the percentage sign and then multiply the percent against another variable thats just a number (e.g. 1000, 12000) and then output the result. Is there a simple way to strip the percentage sign and then calculate the output with PHP? Or should I consider some sort of JS solution?
| 0
| 0
| 0
| 0
| 1
| 0
|
I was given a task. Write an algorithm so that, the input of 2 lists of data, will have at least one in common.
So, this is my algorithm: (I write the code in php)
$arrayA = array('5', '6', '1', '2', '7');
$arrayB = array('9', '2', '1', '8', '3');
$arrayC = array();
foreach($arrayA as $val){
if(in_array($val, $arrayB)){
array_push($arrayC, $val);
}
}
Thats my own algo, not sure if its a good one. So, based on my algorithm, how to find the formula of best case and worst case (big O)?
Note: Please do let me know, if my algorithm is wrong. My goal is " input of 2 lists of data, will have at least one in common."
| 0
| 0
| 0
| 0
| 1
| 0
|
Is there existing software for discriminative reranking, such as that used by the Charniak NLP parser, Shen, Sarkar, and Och's parser or Shen and Joshi's techniques? I'd like something that I can easily adapt for my own uses, which are similar to parse reranking.
| 0
| 1
| 0
| 1
| 0
| 0
|
What's the best way to do base36 arithmetic in Perl?
To be more specific, I need to be able to do the following:
Operate on positive N-digit numbers in base 36 (e.g. digits are 0-9 A-Z)
N is finite, say 9
Provide basic arithmetic, at the very least the following 3:
Addition (A+B)
Subtraction (A-B)
Whole division, e.g. floor(A/B).
Strictly speaking, I don't really need a base10 conversion ability - the numbers will 100% of time be in base36. So I'm quite OK if the solution does NOT implement conversion from base36 back to base10 and vice versa.
I don't much care whether the solution is brute-force "convert to base 10 and back" or converting to binary, or some more elegant approach "natively" performing baseN operations (as stated above, to/from base10 conversion is not a requirement). My only 3 considerations are:
It fits the minimum specifications above
It's "standard". Currently we're using and old homegrown module based on base10 conversion done by hand that is buggy and sucks.
I'd much rather replace that with some commonly used CPAN solution instead of re-writing my own bicycle from scratch, but I'm perfectly capable of building it if no better standard possibility exists.
It must be fast-ish (though not lightning fast). Something that takes 1 second to sum up 2 9-digit base36 numbers is worse than anything I can roll on my own :)
P.S. Just to provide some context in case people decide to solve my XY problem for me in addition to answering the technical question above :)
We have a fairly large tree (stored in DB as a bunch of edges), and we need to superimpose order on a subset of that tree. The tree dimentions are big both depth- and breadth- wise. The tree is VERY actively updated (inserts and deletes and branch moves).
This is currently done by having a second table with 3 columns: parent_vertex, child_vertex, local_order, where local_order is an 9-character string built of A-Z0-9 (e.g. base 36 number).
Additional considerations:
It is required that the local order is unique per child (and obviously unique per parent),
Any complete re-ordering of a parent is somewhat expensive, and thus the implementation is to try and assign - for a parent with X children - the orders which are somewhat evenly distributed between 0 and 36**10-1, so that almost no tree inserts result in a full re-ordering.
| 0
| 0
| 0
| 0
| 1
| 0
|
I am writing a game in Python (with pygame) that requires me to generate random but nice-looking "sea" for each new game. After a long search I settled on an algorithm that involves Bezier curves as defined in padlib.py. I now need to figure out when the curves generated by padlib intersect a line segment.
The brute force method would be to just use the set of approximating line segments produced by padlib to find the answer. However, I suspect that a better answer can be found analytically. I only have a few dozen spline segments - searching them should be faster than thousand of line segments.
A little search took me down this road: Bezier Curve -> Kochanek-Bartels Spline -> Cubic Hermite spline
On the last page, I found this function:
p(t) = h00(t)p0 + h10(t)m0 + h01(t)p1 + h11(t)m1
where p(t) is a actually a point (2-dimensional vector), hij(t) functions are cubic polynomials, p0, p1, m0 and m1 are points I can get from padlib code.
Now, I can see that the solution to my problem is p(t) = u + v * t1, where u and v are the end of my line segment.
However, working out the analytical solution is beyond me. Does anyone here know of an existing solution? Or can help me with solving the equations?
| 0
| 0
| 0
| 0
| 1
| 0
|
So I found some similarities between arrays and set notation while learning about sets and sequences in precalc e.g. set notation: {a | cond } = { a1, a2, a3, a4, ..., an} given that n is the domain (or index) of the array, a subset of Natural numbers (or unsigned integer). Most programming languages would provide similar methods to arrays that are applied to sets e.g. upperbounds & lowerbounds; possibly suprema and infima too.
Where did arrays come from?
| 0
| 0
| 0
| 0
| 1
| 0
|
Please order the function belows by growth rate from fastest to slowest:
n^10
2^n
nlog(n)
10^6
And my answer is:
2^n
n^10
nlog(n)
10^6
Is my answer correct?
| 0
| 0
| 0
| 0
| 1
| 0
|
Mathematically I suppose it's possible that even two random GUIDs generated using the built in method in the .NET framework are identical, but roughly how likely are they to clash if you generate hundreds or thousands?
If you generated one for every copy of Windows in the world, would they clash?
The reason I ask is because I have a program that creates a lot of objects, and destroys some too, and I am wondering about the likelihood of any of those objects (including the destroyed ones) having identical GUIDs.
| 0
| 0
| 0
| 0
| 1
| 0
|
I have a value range from 0 to 255.
There is a method that returns an array with a min and max values within this range, i.e: 13, 15, 20, 27, 50 ... 240
where 13 is the min and 240 is the max
I need to scale these values so that 13 becomes 0 and 240 becomes 255 and scale all the other values between them proportionally.
Is there any C# method that does that?
thanks!
| 0
| 0
| 0
| 0
| 1
| 0
|
I'm searching for an algorithm to calculate the average distance between a point and a line segment in 3D. So given two points A(x1, y1, z1) and B(x2, y2, z2) that represent line segment AB, and a third point C(x3, y3, z3), what is the average distance between each point on AB to point C?
I'm also interested in the average distance between two line segments. So given segment AB and CD, what is the average distance from each point on AB to the closest point on CD?
I haven't had any luck with the web searches I've tried, so any suggestions would be appreciated.
Thanks.
| 0
| 0
| 0
| 0
| 1
| 0
|
For the classic water jugs search problem, even for more than three jugs, which are some admissible functions that can be used for the A* search algorithm?
Edit:
I know about http://www.dave-reed.com/csc550.S02/HW/HW4.html , but that function clearly is not consistent.
| 0
| 1
| 0
| 0
| 0
| 0
|
Do you have some advices or reading how to engineer features for a machine learning task?
Good input features are important even for a neural network. The chosen features will affect the needed number of hidden neurons and the needed number of training examples.
The following is an example problem, but I'm interested in feature engineering in general.
A motivation example:
What would be a good input when looking at a puzzle (e.g., 15-puzzle or Sokoban)? Would it be possible to recognize which of two states is closer to the goal?
| 0
| 1
| 0
| 1
| 0
| 0
|
Just wondering if there was a nice (already implemented/documented) algorithm to do the following
boo! http://img697.imageshack.us/img697/7444/sdfhbsf.jpg
Given any shape (without crossing edges) and two points inside that shape, compute all the paths between the two points such that all reflections are perfect reflections. The path lengths should be limited to a certain length otherwise there are infinite solutions. I'm not interested in just shooting out rays to try to guess how close I can get, I'm interested in algorithms that can do it perfectly. Search based, not guess/improvement based.
| 0
| 0
| 0
| 0
| 1
| 0
|
I am working on a factorisation problem and for small numbers it is working well. I've been able to calculate the factors (getting the answers from Wolfram Alpha) for small numbers, like the one on the Wikipedia page (5959).
Along with the Wikipedia page I have been following this guide. Once again, as my Math knowledge is pretty poor I cannot follow what I need to do next.
EDIT: It finally works! I'll post the working code up here once I've got it fully working so that others in my predicament can learn from it.
| 0
| 0
| 0
| 0
| 1
| 0
|
I am just trying to implement multi-precision arithmetic on native MIPS. Assume that
one 64-bit integer is in register $12 and $13 and another is in registers $14 and $15.
The sum is to be placed in registers $10 and $11. The most significant word of the 64-bit integer is found in the even-numbered registers, and the least significant word is found in the odd-numbered registers. On the internet, it said, this is the shortest possible implementation.
addu $11, $13, $15 # add least significant word
sltu $10, $11, $15 # set carry-in bit
addu $10, $10, $12 # add in first most significant word
addu $10, $10, $14 # add in second most significant word
I just wanna double check that I understand correctly. The sltu checks if
the sum of the two least significant words is smaller or equal than one of
the operands. If this is the case, than did a carry occur, is this right?
To check if there occured a carry when adding the two most significant
words and store the result in $9 I have to do:
sltu $9, $10, $12 # set carry-in bit
Does this make any sense?
| 0
| 0
| 0
| 0
| 1
| 0
|
How can I get the 2 biggers numbers of a matrix row?
If the matrix have a bigger number in other row, it can't be shown.
For example, let's suppose I have the following matrix
int mat[][] ={{1,2,3}{4,5,6}{7,8,9}};
if I search the 2 biggers numbers from the row 0, it should return me the indexes 1 and 2 (values 2 and 3).
| 0
| 0
| 0
| 0
| 1
| 0
|
I have code similar to:
if conditionA(x, y, z) then doA()
else if conditionB(x, y, z) then doB()
...
else if conditionZ(x, y, z) then doZ()
else throw ShouldNeverHappenException
I would like to validate two things (using static analysis):
If all conditions conditionA, conditionB, ..., conditionZ are mutually exclusive (i.e. it is not possible that two or more conditions are true in the same time).
All possible cases are covered, i.e. "else throw" statement will never be called.
Could you recommend me a tool and/or a way I could (easily) do this?
I would appreciate more detailed informations than "use Prolog" or "use Mathematica"... ;-)
UPDATE:
Let assume that conditionA, conditionB, ..., conditionZ are (pure) functions and x, y, z have "primitive" types.
| 0
| 0
| 0
| 0
| 1
| 0
|
For given floating point numbers x and a, I would like to compute r (and n) such that x = a*n + r . In C/C++ this function is called fmod. However I do not see a convenient function in .NET. Math.DivRem is only for integers ...
| 0
| 0
| 0
| 0
| 1
| 0
|
can anyone assist me in finding the proper formula for quad normalization ?
using c++ with opengl.
thank you!
| 0
| 0
| 0
| 0
| 1
| 0
|
I'm working in J2ME, I have my gameloop doing the following:
public void run() {
Graphics g = this.getGraphics();
while (running) {
long diff = System.currentTimeMillis() - lastLoop;
lastLoop = System.currentTimeMillis();
input();
this.level.doLogic();
render(g, diff);
try {
Thread.sleep(10);
} catch (InterruptedException e) {
stop(e);
}
}
}
So it's just a basic gameloop, the doLogic() function calls for all the logic functions of the characters in the scene and render(g, diff) calls the animateChar function of every character on scene, following this, the animChar function in the Character class sets up everything in the screen as this:
protected void animChar(long diff) {
this.checkGravity();
this.move((int) ((diff * this.dx) / 1000), (int) ((diff * this.dy) / 1000));
if (this.acumFrame > this.framerate) {
this.nextFrame();
this.acumFrame = 0;
} else {
this.acumFrame += diff;
}
}
This ensures me that everything must to move according to the time that the machine takes to go from cycle to cycle (remember it's a phone, not a gaming rig). I'm sure it's not the most efficient way to achieve this behavior so I'm totally open for criticism of my programming skills in the comments, but here my problem: When I make I character jump, what I do is that I put his dy to a negative value, say -200 and I set the boolean jumping to true, that makes the character go up, and then I have this function called checkGravity() that ensure that everything that goes up has to go down, checkGravity also checks for the character being over platforms so I will strip it down a little for the sake of your time:
public void checkGravity() {
if (this.jumping) {
this.jumpSpeed += 10;
if (this.jumpSpeed > 0) {
this.jumping = false;
this.falling = true;
}
this.dy = this.jumpSpeed;
}
if (this.falling) {
this.jumpSpeed += 10;
if (this.jumpSpeed > 200) this.jumpSpeed = 200;
this.dy = this.jumpSpeed;
if (this.collidesWithPlatform()) {
this.falling = false;
this.standing = true;
this.jumping = false;
this.jumpSpeed = 0;
this.dy = this.jumpSpeed;
}
}
}
So, the problem is, that this function updates the dy regardless of the diff, making the characters fly like Superman in slow machines, and I have no idea how to implement the diff factor so that when a character is jumping, his speed decrement in a proportional way to the game speed. Can anyone help me fix this issue? Or give me pointers on how to make a 2D Jump in J2ME the right way.
| 0
| 0
| 0
| 0
| 1
| 0
|
Named Entity Extraction (extract ppl, cities, organizations)
Content Tagging (extract topic tags by scanning doc)
Structured Data Extraction
Topic Categorization (taxonomy classification by scanning doc....bayesian )
Text extraction (HTML page cleaning)
are there libraries that i can use to do any of the above functions of NLP ?
dont really feel like forking out cash to AlchemyAPI
| 0
| 1
| 0
| 0
| 0
| 0
|
Im working in a screen coordinate space that is different to that of the classical X/Y coordinate space, where my Y direction goes down in the positive instead of up.
Im also trying to figure out how to make a Circle on my screen always face away from the center point of the screen.
If the center point of my screen is at x(200) y(300) and the point of my circle's center is at x(150) and y(380) then I would like to calculate the angle that the circle should be facing.
At the moment I have this:
Point centerPoint = new Point(200, 300);
Point middleBottom = new Point(200, 400);
Vector middleVector = new Vector(centerPoint.X - middleBottom.X, centerPoint.Y - middleBottom.Y);
Vector vectorOfCircle = new Vector(centerPoint.X - 150, centerPoint.Y - 400);
middleVector.Normalize();
vectorOfCircle.Normalize();
var angle = Math.Acos(Vector.CrossProduct(vectorOfCircle, middleVector));
Console.WriteLine("Angle: {0}", angle * (180/Math.PI));
Im not getting what I would expect.
I would say that when I enter in x(150) and y(300) of my circle, I would expect to see the rotation of 90 deg, but Im not getting that... Im getting 180!!
Any help here would be greatly appreciated.
Cheers,
Mark
| 0
| 0
| 0
| 0
| 1
| 0
|
I've been looking at face detection lately, and a lot of the literature states their outputs have a range. How is this possible? I've created my own network and it only seems to be outputting either -1 or 1. Is this because I'm using the Tanh activation function? I want the values to output from, say, 0 to 1 in a range, rather than a binary output, so I can see how "strong" it thinks the output is actually a face. Thanks.
| 0
| 0
| 0
| 0
| 1
| 0
|
I have two tables of concern here: users and race_weeks. User has many race_weeks, and race_week belongs to User. Therefore, user_id is a fk in the race_weeks table.
I need to perform some challenging math on fields in the race_weeks table in order to return users with the most all-time points.
Here are the fields that we need to manipulate in the race_weeks table.
races_won (int)
races_lost (int)
races_tied (int)
points_won (int, pos or neg)
recordable_type(varchar, Robots can race, but we're only concerned about type 'User')
Just so that you fully understand the business logic at work here, over the course of a week a user can participate in many races. The race_week record represents the summary results of the user's races for that week. A user is considered active for the week if races_won, races_lost, or races_tied is greater than 0. Otherwise the user is inactive.
So here's what we need to do in our query in order to return users with the most points won (actually net_points_won):
Calculate each user's net_points_won (not a field in the DB).
To calculate net_points_won, you take (1000 * count_of_active_weeks) - sum(points__won). (Why 1000? Just imagine that every week the user is spotted a 1000 points to compete and enter races. We want to factor-out what we spot the user because the user could enter only one race for the week for 100 points, and be sitting on 900, which we would skew who actually EARNED the most points.)
This one is a little convoluted, so let me know if I can clarify further.
| 0
| 0
| 0
| 0
| 1
| 0
|
I am looking for an open source library for Linguistic Inquiry and Word Count (LIWC). Something in java or python will be good, though I am open to use other language.
Does anyone know where I can get one ?
Cheers,
| 0
| 1
| 0
| 0
| 0
| 0
|
If you look at the top right you'll see on a radar an enemy unit line of sight.
I was wondering what is the most efficient or easiest way (little code, fairly accurate. doesnt need to be perfect) to detect if something is in your line of sight? I may or may not need to render it (i likely wont).
I dont know the formula nor used any math libs/namespaces in C#
-edit-
Basically this is a 2d prototype. nothing has to be perfect and it will have movable camera, units and it will only look left right up down but not diagonally. There may be a wall blocking line of sight but nothing else. Also other enemies shouldnt trigger an action when they walk into it.
So really i need a source(enemy), a dst (player) and keep account of walls blocking vision.
alt text http://image.com.com/gamespot/images/screenshots/gs/action/metalgearsolid/metalgearsolid_790screen001.jpg
-edit- i ended up using a rect. It was good enough and i was able to work on other thing in the prototype then writing raycast code.
| 0
| 0
| 0
| 0
| 1
| 0
|
For one of my course project I started implementing "Naive Bayesian classifier" in C. My project is to implement a document classifier application (especially Spam) using huge training data.
Now I have problem implementing the algorithm because of the limitations in the C's datatype.
( Algorithm I am using is given here, http://en.wikipedia.org/wiki/Bayesian_spam_filtering )
PROBLEM STATEMENT:
The algorithm involves taking each word in a document and calculating probability of it being spam word. If p1, p2 p3 .... pn are probabilities of word-1, 2, 3 ... n. The probability of doc being spam or not is calculated using
Here, probability value can be very easily around 0.01. So even if I use datatype "double" my calculation will go for a toss. To confirm this I wrote a sample code given below.
#define PROBABILITY_OF_UNLIKELY_SPAM_WORD (0.01)
#define PROBABILITY_OF_MOSTLY_SPAM_WORD (0.99)
int main()
{
int index;
long double numerator = 1.0;
long double denom1 = 1.0, denom2 = 1.0;
long double doc_spam_prob;
/* Simulating FEW unlikely spam words */
for(index = 0; index < 162; index++)
{
numerator = numerator*(long double)PROBABILITY_OF_UNLIKELY_SPAM_WORD;
denom2 = denom2*(long double)PROBABILITY_OF_UNLIKELY_SPAM_WORD;
denom1 = denom1*(long double)(1 - PROBABILITY_OF_UNLIKELY_SPAM_WORD);
}
/* Simulating lot of mostly definite spam words */
for (index = 0; index < 1000; index++)
{
numerator = numerator*(long double)PROBABILITY_OF_MOSTLY_SPAM_WORD;
denom2 = denom2*(long double)PROBABILITY_OF_MOSTLY_SPAM_WORD;
denom1 = denom1*(long double)(1- PROBABILITY_OF_MOSTLY_SPAM_WORD);
}
doc_spam_prob= (numerator/(denom1+denom2));
return 0;
}
I tried Float, double and even long double datatypes but still same problem.
Hence, say in a 100K words document I am analyzing, if just 162 words are having 1% spam probability and remaining 99838 are conspicuously spam words, then still my app will say it as Not Spam doc because of Precision error (as numerator easily goes to ZERO)!!!.
This is the first time I am hitting such issue. So how exactly should this problem be tackled?
| 0
| 0
| 0
| 1
| 0
| 0
|
Relating to this question i was wondering if .NET has any libs (or a function) i can use to detect if one point collides with another.
I am not sure what angles i should use but is there some function like this
func(point src, rect target, angle, distanceOfVision, listPointOrRectOfWalls)
Pretty unlikely but i dont know a formula or how to start. Its a quick and dirty prototype. I am thinking of writing the func but dropping angle making line of sight a rectangle and check if any wall points are between src and target.
| 0
| 0
| 0
| 0
| 1
| 0
|
I'm calculating fixedpoint reciprocals in Q22.10 with Goldschmidt division for use in my software rasterizer on ARM.
This is done by just setting the numerator to 1, i.e the numerator becomes the scalar on the first iteration. To be honest, I'm kind of following the wikipedia algorithm blindly here. The article says that if the denominator is scaled in the half-open range (0.5, 1.0], a good first estimate can be based on the denominator alone: Let F be the estimated scalar and D be the denominator, then F = 2 - D.
But when doing this, I lose a lot of precision. Say if I want to find the reciprocal of 512.00002f. In order to scale the number down, I lose 10 bits of precision in the fraction part, which is shifted out. So, my questions are:
Is there a way to pick a better estimate which does not require normalization? Why? Why not? A mathematical proof of why this is or is not possible would be great.
Also, is it possible to pre-calculate the first estimates so the series converges faster? Right now, it converges after the 4th iteration on average. On ARM this is about ~50 cycles worst case, and that's not taking emulation of clz/bsr into account, nor memory lookups. If it's possible, I'd like to know if doing so increases the error, and by how much.
Here is my testcase. Note: The software implementation of clz on line 13 is from my post here. You can replace it with an intrinsic if you want. clz should return the number of leading zeros, and 32 for the value 0.
#include <stdio.h>
#include <stdint.h>
const unsigned int BASE = 22ULL;
static unsigned int divfp(unsigned int val, int* iter)
{
/* Numerator, denominator, estimate scalar and previous denominator */
unsigned long long N,D,F, DPREV;
int bitpos;
*iter = 1;
D = val;
/* Get the shift amount + is right-shift, - is left-shift. */
bitpos = 31 - clz(val) - BASE;
/* Normalize into the half-range (0.5, 1.0] */
if(0 < bitpos)
D >>= bitpos;
else
D <<= (-bitpos);
/* (FNi / FDi) == (FN(i+1) / FD(i+1)) */
/* F = 2 - D */
F = (2ULL<<BASE) - D;
/* N = F for the first iteration, because the numerator is simply 1.
So don't waste a 64-bit UMULL on a multiply with 1 */
N = F;
D = ((unsigned long long)D*F)>>BASE;
while(1){
DPREV = D;
F = (2<<(BASE)) - D;
D = ((unsigned long long)D*F)>>BASE;
/* Bail when we get the same value for two denominators in a row.
This means that the error is too small to make any further progress. */
if(D == DPREV)
break;
N = ((unsigned long long)N*F)>>BASE;
*iter = *iter + 1;
}
if(0 < bitpos)
N >>= bitpos;
else
N <<= (-bitpos);
return N;
}
int main(int argc, char* argv[])
{
double fv, fa;
int iter;
unsigned int D, result;
sscanf(argv[1], "%lf", &fv);
D = fv*(double)(1<<BASE);
result = divfp(D, &iter);
fa = (double)result / (double)(1UL << BASE);
printf("Value: %8.8lf 1/value: %8.8lf FP value: 0x%.8X
", fv, fa, result);
printf("iteration: %d
",iter);
return 0;
}
| 0
| 0
| 0
| 0
| 1
| 0
|
How would I print the multiples of a list of given numbers in a merged, sorted list?
I.e.
take 10 (multiples [4,5])
gives
4,5,8,10,12,15,16,20,24,25
I've got it working for lists of size 2 or 1 but I need a more general solution :)
| 0
| 0
| 0
| 0
| 1
| 0
|
I've got a rather strange problem. For a Distributed Hash Table I need to be able to do some simple math operations on MD5 hashes. These include a sum (numeric sum represented by the hash) and a modulo operation. Now I'm wondering what the best way to implement these operations is.
I'm using hashlib to calculate the hashes, but since the hashes I get are then string, how do I calculate with them?
| 0
| 0
| 0
| 0
| 1
| 0
|
Let's say there is a sentence:
On March 1, he was born.
Changing it to
He was born on March 1.
doesn't break the sense of the sentence and it is still valid. Shuffling words in any other way would produce weird to invalid sentences. So basically, I'm talking about parts of the sentence, which make the information more specific, but removing them doesn't break the whole sentence. Is there any NLP library in which identifying such parts is available?
| 0
| 1
| 0
| 0
| 0
| 0
|
I'm new to this site, so hopefully you guys don't mind helping a nub.
Anyway, I've been asked to write code to find the shortest cost of a graph tour on a particular graph, whose details are read in from file. The graph is shown below:
http://img339.imageshack.us/img339/8907/graphr.jpg
This is for an Artificial Intelligence class, so I'm expected to use a decent enough search method (brute force has been allowed, but not for full marks).
I've been reading, and I think that what I'm looking for is an A* search with constant heuristic value, which I believe is a uniform cost search. I'm having trouble wrapping my head around how to apply this in Java.
Basically, here's what I have:
Vertex class -
ArrayList<Edge> adjacencies;
String name;
int costToThis;
Edge class -
final Vertex target;
public final int weight;
Now at the moment, I'm struggling to work out how to apply the uniform cost notion to my desired goal path. Basically I have to start on a particular node, visit all other nodes, and end on that same node, with the lowest cost.
As I understand it, I could use a PriorityQueue to store all of my travelled paths, but I can't wrap my head around how I show the goal state as the starting node with all other nodes visited.
Here's what I have so far, which is pretty far off the mark:
public static void visitNode(Vertex vertex) {
ArrayList<Edge> firstEdges = vertex.getAdjacencies();
for(Edge e : firstEdges) {
e.target.costToThis = e.weight + vertex.costToThis;
queue.add(e.target);
}
Vertex next = queue.remove();
visitNode(next);
}
Initially this takes the starting node, then recursively visits the first node in the PriorityQueue (the path with the next lowest cost).
My problem is basically, how do I stop my program from following a path specified in the queue if that path is at the goal state? The queue currently stores Vertex objects, but in my mind this isn't going to work as I can't store whether other vertices have been visited inside a Vertex object.
Help is much appreciated!
Josh
EDIT: I should mention that paths previously visited may be visited again. In the case I provided this isn't beneficial, but there may be a case where visiting a node previously visited to get to another node would lead to a shorter path (I think). So I can't just do it based on nodes already visited (this was my first thought too)
| 0
| 1
| 0
| 0
| 0
| 0
|
I'm implementing the NTRUEncrypt algorithm, according to an NTRU tutorial, a polynomial f has an inverse g such that f*g=1 mod x, basically the polynomial multiplied by its inverse reduced modulo x gives 1. I get the concept but in an example they provide, a polynomial f = -1 + X + X^2 - X4 + X6 + X9 - X10 which we will represent as the array [-1,1,1,0,-1,0,1,0,0,1,-1] has an inverse g of [1,2,0,2,2,1,0,2,1,2,0], so that when we multiply them and reduce the result modulo 3 we get 1, however when I use the NTRU algorithm for multiplying and reducing them I get -2.
Here is my algorithm for multiplying them written in Java:
public static int[] PolMulFun(int a[],int b[],int c[],int N,int M)
{
for(int k=N-1;k>=0;k--)
{
c[k]=0;
int j=k+1;
for(int i=N-1;i>=0;i--)
{
if(j==N)
{
j=0;
}
if(a[i]!=0 && b[j]!=0)
{
c[k]=(c[k]+(a[i]*b[j]))%M;
}
j=j+1;
}
}
return c;
}
It basicall taken in polynomial a and multiplies it b, resturns teh result in c, N specifies the degree of the polynomials+1, in teh example above N=11; and M is the reuction modulo, in teh exampel above 3.
Why am I getting -2 and not 1?
| 0
| 0
| 0
| 0
| 1
| 0
|
I'm trying to round a number to the next smallest power of another number. I'm not particular on which direction it rounds, but I prefer downwards if possible.
The number x that I'm rounding will satisfy: x > 0, and usually fits within the range 0 < x <= 1. Only rarely will it be above 1.
More generally, my problem is: Given a number x, how can I round it to the nearest integer power of some base b?
I would like to be able to round towards arbitrary bases, but the ones I'm most concerned with at the moment is base 2 and fractional powers of 2 like 2^(1/2), 2^(1/4), and so forth. Here's my current algorithm for base 2.
double roundBaseTwo(double x)
{
return 1.0 / (1 << (int)((log(x) * invlog2))
}
Any help would be appreciated!
| 0
| 0
| 0
| 0
| 1
| 0
|
Hi I am displaying a colour as a hex value in php . Is it possible to vary the shade of colour by subtracting a number from the hex value ? What I want to do it display vivid web safe colour but if selected I want to dull or lighten the colour. I know I can just use two shades of colour but I could hundred of potential colours .
to be clear #66cc00 is bright green and #99ffcc is a very pale green . What do i subtract to get the second colour ? is there any formula because I just can get it .
Thanks for any help
Cheers
| 0
| 0
| 0
| 0
| 1
| 0
|
Consider the set of non-decreasing surjective (onto) functions from (-inf,inf) to [0,1].
(Typical CDFs satisfy this property.)
In other words, for any real number x, 0 <= f(x) <= 1.
The logistic function is perhaps the most well-known example.
We are now given some constraints in the form of a list of x-values and for each x-value, a pair of y-values that the function must lie between.
We can represent that as a list of {x,ymin,ymax} triples such as
constraints = {{0, 0, 0}, {1, 0.00311936, 0.00416369}, {2, 0.0847077, 0.109064},
{3, 0.272142, 0.354692}, {4, 0.53198, 0.646113}, {5, 0.623413, 0.743102},
{6, 0.744714, 0.905966}}
Graphically that looks like this:
(source: yootles.com)
We now seek a curve that respects those constraints.
For example:
(source: yootles.com)
Let's first try a simple interpolation through the midpoints of the constraints:
mids = ({#1, Mean[{#2,#3}]}&) @@@ constraints
f = Interpolation[mids, InterpolationOrder->0]
Plotted, f looks like this:
(source: yootles.com)
That function is not surjective. Also, we'd like it to be smoother.
We can increase the interpolation order but now it violates the constraint that its range is [0,1]:
(source: yootles.com)
The goal, then, is to find the smoothest function that satisfies the constraints:
Non-decreasing.
Tends to 0 as x approaches negative infinity and tends to 1 as x approaches infinity.
Passes through a given list of y-error-bars.
The first example I plotted above seems to be a good candidate but I did that with Mathematica's FindFit function assuming a lognormal CDF.
That works well in this specific example but in general there need not be a lognormal CDF that satisfies the constraints.
| 0
| 0
| 0
| 0
| 1
| 0
|
Let's say I have three 32-bit floating point values, a, b, and c, such that (a + b) + c != a + (b + c). Is there a summation algorithm, perhaps similar to Kahan summation, that guarantees that these values can be summed in any order and always arrive at the exact same (fairly accurate) total? I'm looking for the general case (i.e. not a solution that only deals with 3 numbers).
Is arbitrary precision arithmetic the only way to go? I'm dealing with very large data sets, so I'd like to avoid the overhead of using arbitrary precision arithmetic if possible.
Thanks!
| 0
| 0
| 0
| 0
| 1
| 0
|
[Caveat] This is not directly a programing question, but it is something that comes up so often in language processing that I'm sure it's of some use to the community.
Does anyone have a good list of uninteresting (English) words that have been tested by more then a casual look? This would include all prepositions, conjunctions, etc... words that may have semantic meaning, but are often frequent in every sentence, regardless of the subject. I've built my own lists from time to time for personal projects but they've been ad-hoc; I continuously add words that I forgotten as they come in.
| 0
| 1
| 0
| 0
| 0
| 0
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.