text
stringlengths
0
27.6k
python
int64
0
1
DeepLearning or NLP
int64
0
1
Other
int64
0
1
Machine Learning
int64
0
1
Mathematics
int64
0
1
Trash
int64
0
1
I have a quite big development experience and I wonder is it possible to start learning math from scratch. I forgot almost everything I know, even school program. Please give me some guidance on this. Where to start what to do. Are there any math books for developers. May be with exercises to write code or experiment, etc... Any help is appreciated.
0
0
0
0
1
0
I have a course in my current semester in which I'm required to do a project on application of AI. I have decided to do this on game AI. I have 2 basic ideas: implementing an FPS bot(s) or implementing soccer AI. I'm quiet a noob at AI right now, I've implemented basic pathfinding algos (A*, etc), and have studied about Finite state machines, some First Order logic, basic Neural Network stuff(Backpropagation ALgo), and am currently doing a course on Genetic Algorithms. Our main focus is on the bot right now. Our plans include: Each 'bot' would be implemented using a Finite State Machine (FSM), which would contain the possible states the bot could have; & the rules for the action/state changes that are going to take place when it receives an input. In bot group movement, each bot would decide whether to strike, ways to strike; based on range, number of bots, existing fights using Neural Networks. By using genetic algorithms the opponents next move could be anticipated based on repetitive moves. Although I've programmed a few 2d games till now in my free time (like pacman, tetris, etc), I've never really gone into the 3d area. We will most probably be using a 3d engine. We want to concentrate most of our energy on the AI part. We would like not to be bothered with unnecessary details about the animation/3d models, etc. For example, if we could find a framework which has functions like Moveright() which just moves the bot to the right, it would be really awesome. My basic question is : is it too ambitious to go about it in the way we have planned, considering the duration of the project is abour 3 months? Should we go 3d and use a 3d game engine? is it easy to use such engines, if you have no experience with them before? If yes, what kind of engine would be suitable to our project? I came accross another idea, given in the book AI Game programming by example, where the player would have a top down view of the bots. Would that way be more appropriate? Thanks .. sorry about the length of the question .. it's just that my problem is a bit too specific.
0
1
0
0
0
0
How do I add/subtract/multiply and divide integers using only 20 bits instead of 32 bits in C#? Will these operations be faster than 32bit precision? For example this .NET library is featuring 20 and 30 bit arithmetic with different speeds: http://complex-a5.ru/polyboolean/index.html Thanks.
0
0
0
0
1
0
I'm making a simple RTS game. I want it to run very fast because it should work with thousands of units and 8 players. Everything seems to work flawlessly but it seems the line of sight calculation is a bottleneck. It's simple: if an enemy unit is closer than any of my unit's LOS range it will be visible. Currently I use a quite naive algorithm: for every enemy units I check whether any of my units is see him. It's O(n^2) So If there are 8 players and they have 3000 units each that would mean 3000*21000=63000000 tests per player at the worst case. Which is quite slow. More details: it's a stupid simple 2D space RTS: no grid, units are moving along a straight lines everywhere and there is no collision so they can move through each other. So even hundreds of units can be at the same spot. I want to speed up this LOS algorithm somehow. Any ideas? EDIT: So additional details: I meant one player can have even 3000 units. my units have radars so they towards all directions equally.
0
0
0
0
1
0
I'm using OpenTK for a game in C#, and it doesn't come with the project and unproject functions, which convert between world and screen coordinates. Well, it does, but they're deprecated and I couldn't get them to work. I took a shot at implementing them myself based on the opengl spec (see left hand menu, gluProject and gluUnProject, and view in FF, not Chrome). See those formulas, I'm trying to match them. My functions aren't working at all, the points that Project returns are all near the center of my screen, and very close together, even though I'm moving my world point all over the place. Note that OpenTK's math lib doesn't include functions for multiplying a matrix by a vector, so I just did matrix row by vector dot products for each entry in the resulting vector (that's correct, isn't it?) public static Vector3d Project(Vector4d point, Matrix4d projection, Matrix4d modelview, int[] view) { Matrix4d temp = Matrix4d.Mult(projection, modelview); // multiply matrix by vector Vector4d v_prime = new Vector4d( Vector4d.Dot(temp.Row0, point), Vector4d.Dot(temp.Row1, point), Vector4d.Dot(temp.Row2, point), Vector4d.Dot(temp.Row3, point) ); v_prime = Vector4d.Divide(v_prime, v_prime.W); return new Vector3d( view[0] + view[2] * (v_prime.X + 1) / 2, view[1] + view[3] * (v_prime.Y + 1) / 2, (v_prime.Z + 1) / 2 ); } public static Vector3d UnProject(Vector3d window, Matrix4d modelview, Matrix4d projection, int[] view) { Matrix4d inv = Matrix4d.Mult(projection, modelview); inv.Invert(); double vx = (2 * (window.X - view[0])) / view[2] - 1; double vy = (2 * (window.Y - view[1])) / view[3] - 1; double vz = (2 * window.Z) - 1; Vector4d vect = new Vector4d(vx, vy, vz, 1); // now multiply matrix times vector, which is really row (dot) vector for each value // correct, the bottom row of the inv matrix is unused return new Vector3d( Vector4d.Dot(inv.Row0, vect), Vector4d.Dot(inv.Row1, vect), Vector4d.Dot(inv.Row2, vect) ); }
0
0
0
0
1
0
I have a basic solution file (.sln) where I was able to reproduce a problem I have been facing recently. It contains 3 projects: 1.) MathTest.lib - containing methods that might cause a mathematical error, like acos(1.1). 2.) MathTestDll.dll - calls the methods from the above lib. 3.) UnitTest.exe - calls the exported method in the DLL that should cause the error. What I'm trying to do is fairly simple: The following code contains the _matherr() routine and should ideally link fine. The call to acos() with a value of 1.1 is invalid (invalid input) and should cause an error which should be handled by the implemented _matherr() handler. I hope I'm right about the behavior of _matherr(). Please let me know. MathTest.lib #include "MathTest.h" #include <iostream> #include <math.h> int _matherr(_exception* _Except) { std::cout << _Except->name; return -1; } void MathTest::ThrowMatherr(float par) { float result = acos(par); std::cout << result; } This 'ThrowMatherr()' method will be called by the DLL as follows: MathTestDll.dll void MatherrCaller::CauseMatherr() { MathTest* mathtest = new MathTest(); mathtest->ThrowMatherr(1.1); } which is then exported as: extern "C" __declspec(dllexport) void CallThisToCauseMatherr(); void CallThisToCauseMatherr() { MatherrCaller* caller = new MatherrCaller(); caller->CauseMatherr(); } This exported method will be called by a simple test. UnitTest.exe #include <windows.h> typedef void (*METHODTOCALL)(); int main() { HMODULE module = LoadLibrary((LPCSTR)"..\\Debug\\MatherrTestDll.dll"); if(module != NULL) { METHODTOCALL ProcAdd = (METHODTOCALL) GetProcAddress(module, (LPCSTR)"CallThisToCauseMatherr"); if (NULL != ProcAdd) { (ProcAdd)(); } FreeLibrary(module); } return 0; } All methods get called fine. But the acos() method which has been passed invalid input never calls the _matherr() error handler. Please let me know how I can fix this. I had to make the question detailed to get my point through. Please don't mind.
0
0
0
0
1
0
I have the following scenario where i invest variable amount of principal every month, Investment Month $300 Jan $200 Feb $100 Mar and i get a return of, Returns Month $1000 Apr How do i calculate the nominal annual interest rate if the amount is compounded monthly?
0
0
0
0
1
0
Is there any service that provide a public API to perform mathematical calculations (such as linear algebra decompositions etc)? Thanks
0
0
0
0
1
0
Full Disclosure: I am a mathematical moron int hours = totalSeconds / (60 * 60); int minutes = (totalSeconds / 60) % 60; int seconds = totalSeconds % 60; //int milliseconds ??? calculatedExposureTime.text = [NSString stringWithFormat:@"%02d:%02d:%02d:%02d", hours, minutes, seconds, milliseconds]; Say totalSeconds was a fraction of a second (0.000156), how do I calculate and display time down to the millisecond?
0
0
0
0
1
0
I'd like to plot data x & y with errorbars, ebar, and its fit, yfitted, on a semilog plot. This doesn't seem to work: figure; hold on; errorbar(x,y,ebar); semilogy(x,yfitted); Instead of semilog plot I get a linear plot. What should I be doing differently?
0
0
0
0
1
0
I'm working on a simple board game using Appcelerator Titanium for iPhone (javascript - not that it matters for this question really). My problem isn't really language-specific, it's more of a general programming and math question. I have a grid of "cells" that is 10 columns by 10 rows (100 cells). It's a board game, like checkers/draughts. Starting at the top and moving downward, the rows are labeled 'A' through 'J' Starting at the left and moving right, the columns are labeled '0' through '9' Each cell is 32x32 (pixels). I can drag a token onto/over the grid and when I release, it reports to me the x/y coordinates of where I released, eg: 124,302. I have these coords available to me in variables. So my question is, how do I determine the center point of the cell that I released over, so I can center the token in that cell? Any ideas on how to accomplish this?
0
0
0
0
1
0
There are two Sprite's hit tests, one check the object (and have no precision on the curves) and the other check a specified (x, y) point. But, having curves drawn using Graphics.curveTo(), how do I check if 2 drawn curves are colliding? I'm not sure if this is an actionscript or a math problem... I want to check all (x,y) of a curve to all (x,y) of the other curve.. any idea?
0
0
0
0
1
0
Short question: Given a point P and a line segment L, how do I find the point (or points) on L that are exactly X distance from P, if it guaranteed that there is such a point? The longer way to ask this question is with an image. Given two circles, one static and one dynamic, if you move the dynamic one towards the static one in a straight line, it's pretty easy to determine the point of contact (see 1, the green dot). Now, if you move the dynamic circle towards the static circle at an angle, determining the point of contact is much more difficult, (see 2, the purple dot). That part I already have done. What I want to do is, after determining the point of contact, decrease the angle and determine the new point of contact (see 3, 4, the red dot). In #4, you can see the angle is decreased by less than half, and the new point of contact is half-way between the straight-line point and the original point. In #7, you can see the angle is bisected, but the new point of contact moves much farther than half way back towards the straight-line point. In my case, I always want to decrease the angle to 5/6ths its original value, but the original angle and distance between the circles are variable. The circles are all the same radius. The actual data I need after decreasing the angle is the vector between the new center of the dynamic circle and the static circle, that is, the blue line in 3, 4, 6, and 7, if that makes the calculation any easier. So far, I know I have to move the dynamic circle along the line that the purple circle is a center of, towards the center of the static circle. Then the circle has to move directly back towards the original position of the dynamic circle. The hard part is knowing exactly how far back it has to move so that it's just touching the other circle.
0
0
0
0
1
0
I have nearly 1 million photos auto-incremented starting at "1". So, I have the following: 1.jpg 2.jpg 3.jpg 4.jpg 5.jpg .... 1000000.jpg Currently, I have all of these files in a single Ext4 linux directory. As you can imagine, the filesystem is crazy slow. Using PHP, how can I create an algorithm that divides up my images into a directory structure so that each directly has significantly less objects per directory. For example: 1000/1.jpg 1000/2.jpg 1000/3.jpg ... 1000/999.jpg 1000/1000.jpg 2000/1001.jpg 2000/1002.jpg 2000/1003.jpg 2000/1999.jpg How would I divide/modulus/implode/shift the image name (id) into a file structure like such above? UPDATE: Basically, I want to create a PHP function that does the following. Only accept positive integers, not including 0. For values 1-999, return 0 For values 1000-1999, return 1000 For values 10,000-10,999, return 10000 For values 25,000-25,999, return 25000
0
0
0
0
1
0
I came to a career in software development with a degree in English, rather than Computer Science or another science/engineering background. I have gone a long way on my self-taught basis, but after 10+ years of doing this, I want to go back and fill in the gaps, particularly with the math. The obvious place to give myself a Comp-Sci education is to go through The Art of Computer Programming. However, as I didn't take all that much math and my last math class in college was in 1995, I need some brushing up and augmenting to even be able to read the math notation in TAOCP. My thought was to go to Khan Academy and work through the necessary topics as a remedial prereq to reading TAOCP. However, in a Catch 22, I'm trying to figure out which topics do I actually need to go through as prep. So, what I'm wondering is, if someone basically only had high school math (I've got a bit more than that, but I think it's a valid question for someone to approach this with just high school as a background), what math "classes" does one need from somewhere like Khan Academy in order to start TAOCP prepared to read and understand the included math?
0
0
0
0
1
0
How would i turn the secant method of iteration into php? The formula is xi+1= xi - (f(xi) (xi-xi+1))/f(xi)-f(xi-1) where f = function and i is an iteration. so xi+1 is the next iteration after xi So far I have seen this, but there is somethning wrong somewhere in it so i want to make one from scratch, unless someone here can see what is wrong with it? while ((abs($y0 - $y1) > FINANCIAL_ACCURACY) && ($i < FINANCIAL_MAX_ITERATIONS)) { $rate = ($y1 * $x0 - $y0 * $x1) / ($y1 - $y0); $x0 = $x1; $x1 = $rate; if (abs($rate) < FINANCIAL_ACCURACY) { $y = $pv * (1 + $nper * $rate) + $pmt * (1 + $rate * $type) * $nper + $fv; } else { $f = exp($nper * log(1 + $rate)); $y = $pv * $f + $pmt * (1 / $rate + $type) * ($f - 1) + $fv; } $y0 = $y1; $y1 = $y; $i++; } Thanks forgot to add, FINANCIAL_ACCURACY is defined as define('FINANCIAL_ACCURACY', 1.0e-6);
0
0
0
0
1
0
Possible Duplicates: Is JavaScript’s Math broken? How is floating point stored? When does it matter? Code: var tax= 14900*(0.108); alert(tax); The above gives an answer of 1609.2 var tax1= 14900*(10.8/100); alert(tax1); The above gives an answer of 1609.200000000003 why? i guess i can round up the values, but why is this happening? UPDATE: Found a temp solution for the problem. Multiply first: (14900*10.8)/100 = 1609.2 However (14898*10.8)/100 = 1608.9840000000002 For this multiply the 10.8 by a factor(100 in this case) and adjust the denominator: (14898*(10.8*100))/10000 = 1608.984 I guess if one can do a preg_match for the extra 000s and then adjust the factor accordingly, the float error can be avoided. The final solution would however be a math library.
0
0
0
0
1
0
If I have a grid say consisting of 15 x 15 cells (but variable), what formulae or algorithm would I use to randomly select 20 cells clustered around the centre cell? I guess I would ideally like to be able to set the centre point, cluster radius, density etc... any pointers would be really appreciated! cheers.
0
0
0
0
1
0
I understand that y = x ^ n would be float y = (x, n) but what if i wanted to draw the curves y = 1 - x ^ 4 y = (1-x) ^ 4 y = 1-(1-x) ^ 4 Here's the code i wrote but it doesn't draw the curve mathematically correct for y = 1 - x ^ 4 for (int x = 0; x < 100; x++) { float n = norm(x, 0.0, 100.0); float y = pow(1-n, 4); y *= 100; smooth(); point(x, y); }
0
0
0
0
1
0
I have a char[26] of the letters a-z and via nested for statements I'm producing a list of sequences like: aaa, aaz... aba, abb, abz, ... zzy, zzz. Currently, the software is written to generate the list of all possible values from aaa-zzz and then maintains an index, and goes through each of them performing an operation on them. The list is obviously large, it's not ridiculously large, but it's gotten to the point where the memory footprint is too large (there are also other areas being looked at, but this is one that I've got). I'm trying to produce a formula where I can keep the index, but do away with the list of sequences and calculate the current sequence based on the current index (as the time between operations between sequences is long). Eg: char[] characters = {a, b, c... z}; int currentIndex = 29; // abd public string CurrentSequence(int currentIndex) { int ndx1 = getIndex1(currentIndex); // = 0 int ndx2 = getIndex2(currentIndex); // = 1 int ndx3 = getIndex3(currentIndex); // = 3 return string.Format( "{0}{1}{2}", characters[ndx1], characters[ndx2], characters[ndx3]); // abd } I've tried working out a small example using a subset (abc) and trying to index into that using modulo division, but I'm having trouble thinking today and I'm stumped. I'm not asking for an answer, just any kind of help. Maybe a kick in the right direction?
0
0
0
0
1
0
using jquery, how would i find the closest match in an array, to a specified number For example, you've got an array like this: 1, 3, 8, 10, 13, ... What number is closest to 4? 4 would return 3 2 would return 3 5 would return 3 6 would return 8 ive seen this done in many different languages, but not in jquery, is this possible to do simply
0
0
0
0
1
0
I have a video player in flex which constantly plays a movie. Is there a way to see how many times it has played? So each time the movie is played, text filled populates with +1. Thanks, Yan
0
0
0
0
1
0
How do you capture user input related to mathematical fractions. Assuming I would like to present a simple square and ask the user to select 3/4ths of a square. What kind of UI control should we use to first all represent a square (with 4 equal blocks inside) and to have a mechanism to capture user input. Assuming you would like to draw a scale which is 1 meter long and and you have markings for every 10 cm (e.g. 10, 20, 30 ...90, 100). We would like the user to plot 40 cm on the scale. What kind of UI controls are available which will help us in drawing such inputs and capturing student response. Are there any tools or libraries which we can use to build such solutions? Our environment is based on (java, richfaces, jquery ...)
0
0
0
0
1
0
Anybody know how to determine whether two sectors of the same circle intersect? Let's say I have a sector A, expressed by starting and ending angles A1 and A2, and a sector B, expressed by starting angle B1 and ending angle B2. All angles ranges from 0..2*PI radians (or 0..360 degrees). How to determine whether angle A intersects with angle B? I've tried a variation of the two rectangle intersection problem like the following: if(a1 <= b2 && a2 >= b1) { // the sectors intersect } else { // the sectores doesn't intersect } This method is fine as long as no sectors crosses the 0 degrees point. But if any one sector crosses it, the calculation becomes incorrect. The underlying problem is in creating a directional (heading-based) augmented reality application. Sector A is the object whereas Sector B is the viewport. The angles are obtained as follow: A0 = bearing of the object A1 = A0 - objectWidthInRadians A2 = A0 + objectWidthInRadians B0 = heading of the user (device) B1 = B0 - viewportWidthInRadians B2 = B0 + viewportWidthInRadians Thanks in advance.
0
0
0
0
1
0
The problem is that I want to get the original values of B, or the original value of C or A. Here is the code: Dim strA As String = "A" Dim strB As String = "B" Dim strC As String = "C" Dim result As Byte = 0 ' Fetch the byte character code of strings and Xor them all into the result in a sequence. result = result Xor AscW(strA) result = result Xor AscW(strB) result = result Xor AscW(strC) ' the final result value is 64 How to do this? Please help me with the correct solution to this problem. If there can be another parameter which when applied with a formula may reveal the original values: "A", "B", "C". Thank you.
0
0
0
0
1
0
How do I create a custom colour scale ideally in Hex? say from yellow to red, depending on the height of an object? is this a correct way to achieve this or is there a better way without having to convert it at the end?: var r:int = 255; var b:int = 0; var maxHeight:int = 52; var minHeight:int = 21; var scale:int = 255 / (maxHeight-minHeight); var g:int = 255 - ((object.height-minHeight) * scale); var hexColor:uint = RGBtoHEX(r,g,b); private function RGBtoHEX(r:int, g:int, b:int) :uint { return r << 16 | g << 8 | b; }
0
0
0
0
1
0
Is it possible to calculate the value of the mathematical constant, e with high precision (2000+ decimal places) using Python? I am particularly interested in a solution either in or that integrates with NumPy or SciPy.
0
0
0
0
1
0
I'm writing a program which solves a 24-puzzle (5x5 grid) using two heuristic. The first uses how many blocks the incorrect place and the second uses the Manhattan distance between the blocks current place and desired place. I have different functions in the program which use each heuristic with an A* and a greedy search and compares the results (so 4 different parts in total). I'm curious whether my program is wrong or whether it's a limitation of the puzzle. The puzzle is generated randomly with pieces being moved around a few times and most of the time (~70%) a solution is found with most searches, but sometimes they fail. I can understand why greedy would fail, as it's not complete, but seeing as A* is complete this leads me to believe that there's an error in my code. So could someone please tell me whether this is an error in my thinking or a limitation of the puzzle? Sorry if this is badly worded, I'll rephrase if necessary. Thanks EDIT: So I"m fairly sure it's something I'm doing wrong. Here's a step-by-step list of how I'm doing the searches, is anything wrong here? Create a new list for the fringe, sorted by whichever heuristic is being used Create a set to store visited nodes Add the initial state of the puzzle to the fringe while the fringe isn't empty.. pop the first element from the fringe if the node has been visited before, skip it if node is the goal, return it add the node to our visited set expand the node and add all descendants back to the fringe
0
1
0
0
0
0
I have a given line R defined by an angle α. R goes through the origin of my plane. I also do have an rectangle, with known width and height. The rectangle has its bottom left corner on the origin. A new line, parallel to R, is defined by a distance L from R (take A, B, and C as examples). I would like to find out the points where the new line intersects the rectangle (like P1 and P2 for the line A, P3 and P4 for B, and P5 and P6 for C). What is the best way to find it?
0
0
0
0
1
0
Not sure of the best way to ask this question other than: I'm writing a function that will accept a variable called 'x'. function doIt(x){ var y = someformula; //this is just a placeholder for the correct formula return y; } And here's what I expect returned: if (x is between 0 and 9){ y = 0; } if (x is between 10 and 19){ y = 32; } if (x is between 20 and 29){ y = 64; } if (x is between 30 and 39){ y = 96; } and so on.... Any help is appreciated. I'm doing it in JavaScript if it matters.
0
0
0
0
1
0
I'm trying to write an evaluation function for a game of checkers that I'm developing but I can't find the right documentation. I've read several documents on the web witch describe different techniques for either writing one or letting the computer find it(using genetic algorithms or Bayesian learning) but they're too complicated for a novice like me. All documents pointed a reference to "Some studies in machine learning using the game of checkers" by A.L.Samuel but I couldn't get my hands on it yet :(. I've only read the follow up "Some studies in machine learning using the game of checkers -II" and found some good info there, but it doesn't explain what the eval parameters mean (I think I don't have the whole article).
0
1
0
0
0
0
This is a realistic question in my study design needed to be solved. Please help. In a 3-cm2 big circle (area=3-cm2, so calculated radius of this big circle=9.77 mm), I need to put 12 small holes (all of same dimension). They should be evenly distributed with 4mm spacing from each other, and should be as close to the edge of the big circle as possible. How to position these small holes and how to calculate radius of the small holes? Thanks
0
0
0
0
1
0
I am looking for research (published) on AI techniques for reading cookbook recipes. Recipes are a very limited domain that might be doable in a natural language recognition engine with some degree of accuracy. I have in mind writing a program that would allow copy/pasting a recipe from a web browser into the AI and having it determine the title, author, ingredients, instructions, nutritional information, etc. by "reading" the recipe. I would also like to be able to process PDF files (I have a large collection), maybe also just using copy/paste. The output will be some kind of (standard) XML-based format that can be read by a recipe organizer. I have in mind PhD or Masters-level work.
0
1
0
0
0
0
Before I start thanking everybody. Through my application s/w I will read syncro values which will be in angles. When I run Python script, the values are collected in particular variables. Suppose the range is -180 to 180. And I got angle as -180. According to the requirement it should be +/-1 deg window;ie; between 179 and -179. How I will check whether its falling in that range ? angle = -180 tolerance = 1 (in degree) if(180-1) <= -180 <= (-180+1): # statements angle1 = -179 tolerance = 1 if(-170-1)<= -179 <= (-179+1): # statements angle2 = 179 tolerance = 1 if(179-1) <= 179 <= (179+1): # statements will this work for all angle combinations ? what you think ?
0
0
0
0
1
0
I've got a number which is less than 500,000,000 and I want to factorize it in an efficient way. What algorithm do you suggest? Note: I have a time limit of 0.01 sec! I've just written this C++ code but it's absolutely awful! void factorize(int x,vector<doubly> &factors) { for(int i=2;i<=x;i++) { if(x%i==0) { doubly a; a.number=i; a.power=0; while(x%i==0) { a.power++; x/=i; } factors.push_back(a); } } } and doubly is something like this: struct doubly { int number; int power; //and some functions!! }; just another point: I know that n is not a prime
0
0
0
0
1
0
I would like an algorithm for a function that takes n integers and returns one integer. For small changes in the input, the resulting integer should vary greatly. Even though I've taken a number of courses in math, I have not used that knowledge very much and now I need some help... An important property of this function should be that if it is used with coordinate pairs as input and the result is plotted (as a grayscale value for example) on an image, any repeating patterns should only be visible if the image is very big. I have experimented with various algorithms for pseudo-random numbers with little success and finally it struck me that md5 almost meets my criteria, except that it is not for numbers (at least not from what I know). That resulted in something like this Python prototype (for n = 2, it could easily be changed to take a list of integers of course): import hashlib def uniqnum(x, y): return int(hashlib.md5(str(x) + ',' + str(y)).hexdigest()[-6:], 16) But obviously it feels wrong to go over strings when both input and output are integers. What would be a good replacement for this implementation (in pseudo-code, python, or whatever language)?
0
0
0
0
1
0
There have been many threads started over the confusion in the way that Math.Round works. For the most part, those are answered by cluing people in to the MidpointRounding parameter and that most people are expecting MidpointRounding.AwayFromZero. I have a further question though about the actual algorithm implemented by AwayFromZero. Given the following number (the result of a number of calculations): 13.398749999999999999999999999M our users are expecting to see the same result that Excel would give them 13.39875. As they are currently rounding that number to 4 using Math.Round(num, 4, MidpointRounding.AwayFromZero), the result is off by .0001 from what they expect. Presumably, the reason for this is that the algorithm just looks at the fifth digit (4), and then rounds accordingly. If you were to start rounding at the last 9, the real mathematical answer would in fact give you the same number as excel. So the question is ... is there a way to emulate this behavior rather than the current? I've written a recursive function that we could use in the meantime. But before we put it in production I wanted to see what SO thought about the problem :-) private decimal Round(decimal num, int precision) { return Round(num, precision, 28); } private decimal Round(decimal num, int precision, int fullPrecision) { if (precision >= fullPrecision) return Math.Round(num, precision); return Round(Math.Round(num, fullPrecision), precision, --fullPrecision); } Edit: just for clarity, I should have been clearer in my original post. The position of rounding methodology being asked for here is what I'm being presented by the business analysts and users who are reporting the "rounding error". Despite being told numerous times that it's not incorrect, just different than what they are expecting ... this report keeps coming in. So I am just on a data gathering stint to gather as much information as I can on this topic to report back to the users. In this case, it seems that any other system used to generate these average prices (which we must match) are using a different level precision (10 in the database, and excel seems to default to 15 or something). Given that everyone has a different level of precision, I'm stuck in the middle with the question of moving to a lower precision, some weird rounding rules (as described above), or just having different results than the users expect.
0
0
0
0
1
0
I am using this right now... if($('.current').hasClass('odd') && !$('.current').hasClass('even')) { var oddMarL = $('.current img').css('margin-left'); var oddMarL2 = $('.touch').css('margin-left'); var oddMarT = $('.touch').css('margin-top'); oddMarL.replace('px', ''); oddMarL2.replace('px', ''); oddMarT.replace('px', ''); Math.abs(oddMarL,oddMarL2,oddMarT); oddMarL = oddMarL + oddMarL2; $('#zoom').css('margin-left',oddMarL); $('#zoom').css('margin-top',oddMarT); } Is there something wrong with my code or is it just not possible? It works until I add the 2 values together or when I use math.abs. In the error console it says margin-left cannot be parsed. I have reasons for needing it this way so please don't recommend using a class! :) thanks.
0
0
0
0
1
0
Non-standard mathematical analysis extends the real number line to include "hyperreals" -- infinitesimals and infinite numbers. Is there (specification for an) implementation of a data type to implement computations using hyperreals? I'm looking for something analogous to the complex number data type you find in Python and Fortran and elsewhere. I actually don't know if such computations are useful: I'm just curious. I've played around with this concept a bit, but since I probably made errors I will spare you-all the details. Reference wikipedia page on hyperreals.
0
0
0
0
1
0
Given an integer n and a positive real number s, how can I partition an interval [0..1] into n intervals such that L(i+1)=s L(i) where L(i) is length of i'th interval? Looking for solution in Mathematica or self-contained C-like pseudo-code
0
0
0
0
1
0
How could I change a random non-uniform distribution to a uniform distribution? Is there a formula?
0
0
0
0
1
0
This is somewhat related to another question I asked: Translate GPS coordinates to location on PDF Map. That got me to this point, now I'm stuck on the math. Let's say I have a floor plan of a building, I've taken gps coordinate readings from each corner of the building. Also assume that the floor plan is lined up with the latitude and longitude. How do I convert a GPS coordinate to a X,Y position on this map? I can't seem to get the math right.
0
0
0
0
1
0
I have a polynomial P and I would like to find y such that P(y) = 0 modulo 2^r. I have tried something along the lines of Hensel lifting, but I don't know if this could even work, because of the usual condition f'(y mod 2) != 0 mod 2 which is not usually true. Is there a different algorithm available ? Or could a variation of Hensel lifting work ? Thanks in advance
0
0
0
0
1
0
I'm trying to understand the reason for a rule when converting. I'm sure there must be a simple explanation, but I can't seem to wrap my head around it. Appreciate any help! Converting from base10 to any other base is done like this: number / desiredBase = number + remainder You do this until number = 0. But after all of the calculations, you have to take all the remainders upside down. I don't understand why. For example: base10 number to base2 11 / 2 = 5 + 1 5 / 2 = 2 + 1 2 / 2 = 1 + 0 1 / 2 = 0 + 1 Why is the correct answer: 1011 and not 1101 ? I know it's a little petty, but it would really help me remember better if I could understand this.
0
0
0
0
1
0
I have a list of strings that are all early modern English words ending with 'th.' These include hath, appointeth, demandeth, etc. -- they are all conjugated for the third person singular. As part of a much larger project (using my computer to convert the Gutenberg etext of Gargantua and Pantagruel into something more like 20th century English, so that I'll be able to read it more easily) I want to remove the last two or three characters from all of those words and replace them with an 's,' then use a slightly modified function on the words that still weren't modernized, both included below. My main problem is that I just never manage to get my typing right in Python. I find that part of the language really confusing at this point. Here's the function that removes th's: from __future__ import division import nltk, re, pprint def ethrema(word): if word.endswith('th'): return word[:-2] + 's' Here's the function that removes extraneous e's: def ethremb(word): if word.endswith('es'): return word[:-2] + 's' hence the words 'abateth' and 'accuseth' would pass through ethrema but not through ethremb(ethrema), while the word 'abhorreth' would need to pass through both. If anyone can think of a more efficient way to do this, I'm all ears. Here's the result of my very amateurish attempt to use these functions on a tokenized list of words that need modernizing: >>> eth1 = [w.ethrema() for w in text] Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: 'str' object has no attribute 'ethrema' So, yeah, it's really an issue of typing. These are the first functions I've ever written in Python, and I have no idea how to apply them to actual objects.
0
1
0
0
0
0
I've got a table of values telling me how the signal level changes over time and I want to simulate a harmonic oscillator driven by this signal. It does not matter if the simulation is not 100% accurate. I know the frequency of the oscillator. I found lots of formulas but they all use a sine wave as driver.
0
0
0
0
1
0
For my tile-based game, I need to calculate direction based on a given point offset (difference between two points). For example, let's say I'm standing at point (10, 4) and I want to move to point (8, 6). The direction I move at is north-west. What would be the best way to calculate this? Here's me basic implementation in Java. public int direction(int x, int y) { if (x > 0) { if (y > 0) { return 0; // NE } else if (y < 0) { return 1; // SE } else { return 2; // E } } else if (x < 0) { if (y > 0) { return 3; // NW } else if (y < 0) { return 4; // SW } else { return 5; // W } } else { if (y > 0) { return 6; // N } else if (y < 0) { return 7; // S } else { return -1; } } } Surely it can be optimised or shortened. Any help? Thanks.
0
0
0
0
1
0
Given 2 functions Translate(x,y) and Scale(x), I want the camera's position to always be the center of the screen. There is also a scalefactor variable and by modifying it it either zooms in or out from the center of the screen. Given that I know the dimensions of the screen in pixels, how could I achieve this? Thanks
0
0
0
0
1
0
I have a 4-control-point bezier curve that represents some timing stuff. The first control is fixed at (0, 0) and the last control is fixed at (1, 1). The two points in between define a bezier curve that specifies how I get from 0 to 1. Now I need to create a second curve, based off the first one. This second curve also needs to go from (0, 0) to (1, 1). But I'd like to to have the shape of some fraction of the first curve, for example it should look like the first 0.75 of the first curve. In other words, if I'm using these curves for timing purposes, and I trace curve #1 for 10 seconds, and simultaneously trace curve #2 for 7.5 seconds, they follow the same path during the time they're both being traced. (Make sense?) Is there a way to take the control points of the first curve and "scale" them into the second curve, given that fractional (0.75 in this example) parameter? Thanks.
0
0
0
0
1
0
Does anyone know a very simple physics engine, or just a set of basic functions that could complete these tasks: Simple point, line, and rectangle collision detection? I looked at Box2D but it is way too advanced for what I am making. I just need some simple code. Thanks in advance!
0
0
0
0
1
0
I am writing a program that creates ICC color formats. These formats specify a data type called s15Fixed16Number which has a sign bit, 15 integer bits and 16 fractional bits. IEEE 754 32-bit floats have a sign bit, 8 exponent bits and 23 fractional bits. I need to get input from a text box, and convert them into a s15Fixed16Number. Some searching turned up this on Google books, but that is talking about converting a decimal number to a s15Fixed16Number. I suppose I could just use the method explained in the link, but I haven't done any testing yet to determine how accurate that would be. I guess I could also try to convert the character input from the text box, but I haven't thought about that much yet. I'm using Cocoa but I don't think that matters; any C function should work. Here are some example values in s15Fixed16Number format: -32768.0 = 0x80000000 0 = 0x00000000 1.0 = 0x00010000 32767 + (65535/65536) = 0x7FFFFFFF I guess it's been awhile since that numerical computation class!
0
0
0
0
1
0
I need to determine the X-radius & Y-radius of an ellipse give the major & minor radius and I couldn't find any way how to do it. I have following inputs: Center Point Start Point Major Radius Minor Radius So, My question is how to create the ellipse rect that should be passed to GDI api i.e. DrawEllipse to draw the ellipse. Thanks & Regards, Pankaj
0
0
0
0
1
0
i have a number variable, vx, that is changing with an enter frame event. in the enter frame function i have the following code: if (Math.abs(vx) <= 0.05); { trace(Math.abs(vx)); } immediately, it's starts outputting numbers that are well above 0.05: 12.544444075226783 12.418999634474515 12.29480963812977 12.171861541748472 12.050142926330986 11.929641497067676 11.810345082097 11.69224163127603 11.575319214963269 11.459566022813636 11.3449703625855 11.231520658959644 11.119205452370048 11.008013397846348 10.897933263867884 10.788953931229205 10.681064391916912 10.574253747997743 10.468511210517764 10.363826098412586 10.260187837428461 10.157585959054176 10.056010099463634 9.955449998468998 9.855895498484308 does this make sense to anyone?
0
0
0
0
1
0
We have a requirement in which we need to change change the words or phrases in the sentence while keeping its meaning intact. This application is going to provide suggestions to users who are involved in copy-writing. I don't know where should I start... we have not yet finalized the technology but would like to do it in a Python or in .Net.
0
1
0
0
0
0
I want to incrementally cluster text documents reading them as data streams but there seems to be a problem. Most of the term weighting options are based on vector space model using TF-IDF as the weight of a feature. However, in our case IDF of an existing attribute changes with every new data point and hence previous clustering does not remain valid anymore and hence any popular algorithms like CluStream, CURE, BIRCH cannot be applied which assumes fixed dimensional static data. Can anyone redirect me to any existing research related to this or give suggestions? Thanks !
0
0
0
1
0
0
iam using the swt java library and iam having a problem. the gc draw arc method takes the following arguments GC.drawArc(int x, int y, int width, int height, int startAngle, int endAngle); but i want to be able to draw the arc using 3 arguments : the source ,destination and control points. is there any formula to convert between those parameters ? QuadCurve2D class do exactly what i want but it is AWT not swt ...and i tried to use java2d under swt but it was very slow .... any solutions ? UPDATE: i have found a solution : using the the createArcByCenter method in Arc2d Object i can give it the 3 parrameters then get the equivalent x , y, width and height ..to use them with gc object are there any better solutions ?
0
0
0
0
1
0
I am trying to score similarity between posts from social networks, but didn't find any good algorithms for that, thoughts? I just tried Levenshtein, JaroWinkler, and others, but those one are more used to compare texts without sentiments. In posts we can get one text saying "I really love dogs" and an other saying "I really hate dogs", we need to classify this case as totally different. Thanks
0
1
0
0
0
0
I want to get some suggestions for my "find similar people" algorithm :). I have one database where I store the following entities: Person, article, keywords. So for each person I have a collection of keywords (with the number of mentions by the person) that have been compiled from person's articles keywords. So I need to get similar people by looking at their relevant keywords, the simple solution would be to get x keywords from a person y and find all people that share similar keyword scores (not equal), but seems that is not the best way. Thoughts? Thanks!
0
1
0
0
0
0
I've trained a system on SVM,that is given a question,whether the webpage is a good one for answering this question. The feature I selected are "Term frequency in webpage","Whether term matches with the webpage title", "number of images in the webpage", "length of the webpage","is it a wikipedia page?","the position of this webpage in the list returned by the search engine". Currently,my system will maintain a precision around 0.4 and recall at 1.It has a large portion of false positive error(that many bad links were classified as good link by my classifier). Since the accuracy could be improved a bit,I would like to ask for some help here on considering refine the features that I selected for training/testing,could remove some or adding more in there. Thanks in advance.
0
1
0
0
0
0
I'm struggling with the following bit of code(/challenge) and I was wondering what would be the best way to solve it. Pseudo(-like) code If I understand the code correctly it does: var val = 1 foreach (char in firstargument): val = val * ((ascii)char + 27137) if (val == 92156295871308407838808214521283596197005567493826981266515267734732800) print "correct" else print "incorrect" Where 'firstargument' is an argument passed to the program like: ./program 123456... Actual code #define _GNU_SOURCE #include <unistd.h> #include <string.h> #include <stdio.h> #include <gmp.h> int main(int argc, char *argv[]) { mpz_t val, mul, cmpval; char str[513]; int n = 0; mpz_init(val); mpz_set_ui(val, 1); mpz_init(mul); mpz_init(cmpval); mpz_set_str(cmpval, "92156295871308407838808214521283596197005567493826981266515267734732800", 10); if (argc < 2) { printf("%s <string> ", argv[0]); return -1; } strncpy(str, argv[1], 512); for (n = 0; n < strlen(str); n++) { mpz_set_ui(mul, (unsigned long)(str[n] + 27137)); mpz_mul(val, val, mul); } if (!(n = mpz_cmp(val, cmpval))) { printf("correct. "); } else { printf("incorrect. "); } return 0; }
0
0
0
0
1
0
I'm trying to write a force-directed or force-atlas code base for a graphing application I'm building for myself. Here is an example of what I'm attempting: http://sawamuland.com/flash/graph.html I managed to find some pseudo code to accomplish what I'd like on the Wiki Force-atlas article. I've converted this into ActionScript 3.0 code since it's a Flash application. Here is my source: var timestep:int = 0; var damping:int = 0; var total_kinetic_engery:int = 0; for (var node in list) { var net_force:int = 0; for (var other_node in list) { net_force += coulombRepulsion(node, other_node, nodeList); } for (var spring in list[node].relations) { net_force += hookeAttraction(node, spring, nodeList); } list[node].velocity += (timestep * net_force) * damping; list[node].position += timestep * list[node].velocity; total_kinetic_engery += list[node].mass * (list[node].velocity) ^ 2; } The problem now is finding pseudo code or a function to perform the the coulomb repulsion and hooke attraction code. I'm not exactly sure how to accomplish this. Does anyone know of a good reference I can look at...understand and implement quickly? Best.
0
0
0
0
1
0
My maths in this area is a bit shaky. Does anybody know how I can calculate a power such as 10^2.2 using no maths functions other than */-+ and a for loop? I don't have access to a maths library (and can't import/include it), but need to calculate these things. Hmm.. maybe I should just look how the math library does it.
0
0
0
0
1
0
It's part of the process of OCR,which is : How to segment the sentences into words,and then characters? What's the candidate algorithm for this task?
0
1
0
1
0
0
I am working on testing several Machine Learning algorithm implementations, checking whether they can work as efficient as described in the papers and making sure they could offer a great power to our statistic NLP (Natural Language Processing) platform. Could u guys show me some methods for testing an algorithm implementation? 1)What aspects? 2)How? 3)Do I have to follow some basic steps? 4)Do I have to consider diversity specific situations when using different programming languages? 5)Do I have to understand the algorithm? I mean, does it offer any help if I really know what the algorithm is and how it works? Basically, we r using C or C++ to implement the algorithm and our working env is Linux/Unix. Our testing methods only focus on black box testing and testing input/output of functions. I am eager to improve them but I dont have any better idea now... Great Thx!! LOL
0
0
0
1
0
0
I have a line that I must do calculations on for each grid square the line passes through. I have used the Superline algorithm to get all these grid squares. This gives me an array of X,Y coordinates to check. Now, here is where I am stuck, I need to be able to calculate the distance traveled through each of the grid squares... As in, on a line not on either 90 degree or 45 degree angles, each grid square accommodates a different 'length' of the total line. Image example here, need 10 reputation to post images As you can see, some squares have much more 'line length' in them than others - this is what I need to find. How do I work this out for each grid square? I've been at this for a while and request the help of the Stack Overflowers!
0
0
0
0
1
0
I have an equation for a parabolic curve intersecting a specified point, in my case where the user clicked on a graph. // this would typically be mouse coords on the graph var _target:Point = new Point(100, 50); public static function plot(x:Number, target:Point):Number{ return (x * x) / target.x * (target.y / target.x); } This gives a graph such as this: I also have a series of line segments defined by start and end coordinates: startX:Number, startY:Number, endX:Number, endY:Number I need to find if and where this curve intersects these segments (A): If it's any help, startX is always < endX I get the feeling there's a fairly straight forward way to do this, but I don't really know what to search for, nor am I very well versed in "proper" math, so actual code examples would be very much appreciated. UPDATE: I've got the intersection working, but my solution gives me the coordinate for the wrong side of the y-axis. Replacing my target coords with A and B respectively, gives this equation for the plot: (x * x) / A * (B/A) // this simplifies down to: (B * x * x) / (A * A) // which i am the equating to the line's equation (B * x * x) / (A * A) = m * x + b // i run this through wolfram alpha (because i have no idea what i'm doing) and get: (A * A * m - A * Math.sqrt(A * A * m * m + 4 * b * B)) / (2 * B) This is a correct answer, but I want the second possible variation. I've managed to correct this by multiplying m with -1 before the calculation and doing the same with the x value the last calculation returns, but that feels like a hack. SOLUTION: public static function intersectsSegment(targetX:Number, targetY:Number, startX:Number, startY:Number, endX:Number, endY:Number):Point { // slope of the line var m:Number = (endY - startY) / (endX - startX); // where the line intersects the y-axis var b:Number = startY - startX * m; // solve the two variatons of the equation, we may need both var ix1:Number = solve(targetX, targetY, m, b); var ix2:Number = solveInverse(targetX, targetY, m, b); var intersection1:Point; var intersection2:Point; // if the intersection is outside the line segment startX/endX it's discarded if (ix1 > startX && ix1 < endX) intersection1 = new Point(ix1, plot(ix1, targetX, targetY)); if (ix2 > startX && ix2 < endX) intersection2 = new Point(ix2, plot(ix2, targetX, targetY)); // somewhat fiddly code to return the smallest set intersection if (intersection1 && intersection2) { // return the intersection with the smaller x value return intersection1.x < intersection2.x ? intersection1 : intersection2; } else if (intersection1) { return intersection1; } // this effectively means that we return intersection2 or if that's unset, null return intersection2; } private static function solve(A:Number, B:Number, m:Number, b:Number):Number { return (m + Math.sqrt(4 * (B / (A * A)) * b + m * m)) / (2 * (B / (A * A))); } private static function solveInverse(A:Number, B:Number, m:Number, b:Number):Number { return (m - Math.sqrt(4 * (B / (A * A)) * b + m * m)) / (2 * (B / (A * A))); } public static function plot(x:Number, targetX:Number, targetY:Number):Number{ return (targetY * x * x) / (targetX * targetX); }
0
0
0
0
1
0
How do you get row back out of n? local n = row * cols + col local c = n % cols local r = ?
0
0
0
0
1
0
I'd like to write an application, which would imitate a player in an online game. About the game: it is a strategy, where you can: train your army (you have to have enough resources, then click on a unit, click train) build buildings (mines, armories, houses,...) attack enemies (select a unit, select an enemy, click attack) transport resources between buildings make researches (economics, military, technologic,...) This is a simplified list and is just an example. Main thing is, that you have to do a lot of clicking, if you want to advance... I allready have the 'navigational' part of the application (I used Watin library - http://watin.sourceforge.net/). That means, that I can use high level objects and manipulate them, for example: Soldiers soldiers = Navigator.GetAllSoldiers(); soldiers.Move(someLocation); Now I'd like to take the next step - write a kind of AI, which would simulate my gaming style. For this I have two ideas (and I don't like either of them): login to the game and then follow a bunch of if statements in a loop (check if someone is attacking me, check if I can build something, check if I can attack somebody, loop) design a kind of scripting language and write a compiler for it. This way I could write simple scripts and run them (Login(); CheckForAnAttack(); BuildSomething(); ...) Any other ideas? PS: some might take this as cheating and it probably is, but I look on this as a learning project and it will never be published or reselled.
0
1
0
0
0
0
I'm trying to achieve an object rotation about 3 axes by incrementing values of rotation angles for axes, and displaying those axes to make next rotation direction predictable for the viewer. But after a few rotations, only rotation about Z-axis is performed in accord with displayed axis. Is there a chance it can be done simply, without poring over quaternions? glPushMatrix (); glRotatef (angleX, 1.0, 0.0, 0.0); glRotatef (angleY, 0.0, 1.0, 0.0); glRotatef (angleZ, 0.0, 0.0, 1.0); glBegin(GL_LINES); glVertex3f(80.0, 0.0, 0.0); //x axis glVertex3f(-80.0, 0.0, 0.0); glVertex3f(0.0, 80.0, 0.0); //y axis glVertex3f(0.0, -80.0, 0.0); glVertex3f( 0.0, 0.0, 80.0); //z axis glVertex3f( 0.0, 0.0, -80.0); //here is some code for drawing arrows at axes ends glEnd(); glPopMatrix(); Edit: I have axes like those: http://img841.imageshack.us/i/arrowsx.jpg/ angleX, angleY, angleZ are globals incremented on key press - e.g. after pressing 'A' angleX is incremented by 10, and I expect axis X won't move after that and axes Y and Z will rotate about axis X. But it is true only when I change only one of angle variables. After rotation about more then one axis, when I change, e.g. angleX - all axes from picture will change their positions.
0
0
0
0
1
0
I am currently trying to construct the area covered by a device over an operating period. The first step in this process appears to be constructing a polygon of the covered area. Since the pattern is not a standard shape, convex hulls overstate the covered area by jumping to the largest coverage area possible. I have found a paper that appears to cover the concept of non-convex hull generation, but no discussions on how to implement this within a high level language. http://www.geosensor.net/papers/duckham08.PR.pdf Has anyone seen a straight forward algorithm for constructing a non-convex hull or concave hull or perhaps any python code to achieve the same result? I have tried convex hulls mainly qhull, with a limited edge size with limited success. Also I have noticed some licensed libraries that will not be able to be distributed, so unfortunately thats off the table. Any better ideas or cookbooks?
0
0
0
0
1
0
im not sure if this is php or mysql maths question. Ive got a table full of data, and although i can echo the individual data to the screen or echo and individual piece of data using php. I've no idea how to perform maths on the data itself. For simplicity, say my table has 4 columns, an id column and three with my data i want to multiply in them, data1, data2 and data 3, and is layed out something like this id data1 data2 data3 1 2.5 2.6 2.7 2 2.6 7.0 8.2 3 3.0 1.8 6.0 what i want to be able to do maths like the following....data1(row1) x data(row2) x data3(row) or data1(column2) x data(column 3) x data3(column3). Im able to use a while loop to loop thru the data, but i can only echo each row with the various field names and its values to the screen. ive no idea how to multiply fields in different rows together. Actually i would also like to be able to now only multiple the rows together, but also add them, divide them etc. The final table of data im likely to need to do this on is likely to include many columns and have multiple rows. yet im basically stuck as to how to get all the data, one from each column and get it to do maths on it one at a time, being putting it in a loop? any ideas cheers
0
0
0
0
1
0
Simulating Ocean Water: http://www.finelightvisualtechnology.com/docs/coursenotes2004.pdf I'm trying to simulate ocean and I need your help. Please be patient, I'm newbie to computer graphics but I know basics of physics and mathematics. As you can see I need to compute the formula: k is a vector, x is a coordinate (so I suggest that it could be equal to vector?). So, first question: how to compute e to the power of such strange thing? Second, it says that h(x,t) is height and also that to get the value it's needed to do FFT. I can't understand it.
0
0
0
0
1
0
This was a contest Q: There are N numbers a[0],a[1]..a[N - 1]. Initally all are 0. You have to perform two types of operations : Increase the numbers between indices A and B by 1. This is represented by the command "0 A B" Answer how many numbers between indices A and B are divisible by 3. This is represented by the command "1 A B". Input : The first line contains two integers, N and Q. Each of the next Q lines are either of the form "0 A B" or "1 A B" as mentioned above. Output : Output 1 line for each of the queries of the form "1 A B" containing the required answer for the corresponding query. Sample Input : 4 7 1 0 3 0 1 2 0 1 3 1 0 0 0 0 3 1 3 3 1 0 3 Sample Output : 4 1 0 2 Constraints : 1 <= N <= 100000 1 <= Q <= 100000 0 <= A <= B <= N - 1 I have no idea how to solve this. can you help please? The time limit is 1 second. I tried brute force and i also tried saving number of divisors of 3 coming before ith element for each i. here's my C code: #include <stdio.h> int nums[100*1000+20]; int d[100*1000+20]; int e[100*1000+20]; int dah[100*1000+20]; int main() { int n,q; scanf("%d%d",&n,&q); int h; for(h=0;h<n;h++) {d[h/100]++; e[h/1000]++; dah[h/10]++;} int test; for(test=0;test<q;test++) { int op,start,end; scanf("%d%d%d",&op,&start,&end); if(0==op) { int x; for(x=start;x<=end;x++) { nums[x]++; nums[x]%=3; if(nums[x]==0) { d[x/100]++; e[x/1000]++; dah[x/10]++; } else if(nums[x]==1) { d[x/100]--; e[x/1000]--; dah[x/10]--; } } } else if(1==op) { int f; int ans=0; for(f=start;f<=end;) { if(f%1000==0&&f+1000<end) { ans+=e[f/1000]; f+=1000; } else if(f%100==0&&f+100<end) { ans+=d[f/100]; f+=100; } else if(f%10==0&&f+10<end) { ans+=dah[f/10]; f+=10; } else { ans+=(nums[f]==0); f++; } } printf("%d ",ans); } } return 0; } In this approach I save number of multiples of 3 between k*1000 and (k+1)*1000 and also the same thing for k*100 and (k+1)*100 and also for 10. this helps me query faster. but this yet gives me time limit exceed.
0
0
0
0
1
0
I apologize if this question is a little broad. Hopefully your answers will help me narrow it down to more meaningful questions. I'm experienced in software engineering and had a recent conversation with a friend who suggested that electrical engineering is very software driven these days. I'm trying to improve my understanding of the electrical engineering side of things and thought since I already know software, a good way could be to write software or a library that's relevant for electrical engineers. Of course I'd prefer to write something that's relevant to as many people as possible so it's not only training for me, but also useful to other. So my plan is to write a library and open source it for several researchers and academics to use. For those who've worked with electrical engineers in the past or who are ee themselves, what do you suggest could be a useful software to have. I'm experienced in several languages mainly PHP, JAVA, C, C++, Actionscript, and a few others. Please suggest a project that you think would be useful to others and the language that would make the most sense for it. Of course if you have anything else in mind, don't hesitate to say it.
0
1
0
0
0
0
I have a differential drive robot, using odometery to infer its position. I am using the standard equations: WheelBase = 35.5cm; WheelRadius = 5cm; WheelCircumference = (WheelRadius * 2 * Math.PI); WheelCircumferencePerEncoderClick = WheelCircumference / 360; DistanceLeft = WheelCircumferencePerEncoderClick * EncoderCountLeft DistanceRight = WheelCircumferencePerEncoderClick * EncoderCountRight DistanceTravelled = (DistanceRight + DistanceLeft) / 2 AngleChange (Theta) = (DistanceRight - DistanceLeft) / WheelBase My (DIY) chassis has as a slight feature, where over the course of the wheel base (35.5cm), the wheels are misaligned, in that the left wheel is 6.39mm (I'm a software person not a hardware person!) more 'forwards' than the right wheel. (The wheels are the middle of the robot.) I'm unsure how to calculate what I must add to my formulas to give me the correct values.. It doesn't affect the robot much, unless it does on the spot turns, and my values are way off, I think this is causing it. My first thought was to plot the wheel locations on a grid, and calculate the slope of the line of their positions, and use that to multiply... something. Am I on the right track? Can someone lend a hand? I've looked around for this error, and most people seem to ignore it (since they are using professional chassis).
0
0
0
0
1
0
I am refreshing my memory on C# (first used it several years ago), and I want to look at some real world quality code (rather than the simplistic ones used in many books). My preference would be mathematical/statistics libraries written in C# as I would like to see how Matrices and PDEs (partial differential equations etc) are implemented in C#. Can anyone recommend a good quality online resource where I can view some 'industrial grade' preferably (Math/Stats) library/application written in C#?
0
0
0
0
1
0
I was thinking about ways to solve this other question about counting the number of values whose digits sum to a target, and decided to try the case where the range was of the form [0, n^base). So essentially you get N independent digits to work with, which is a simpler problem. The number of ways N natural numbers can sum to a target T is easy to compute. If you think of it as placing N-1 dividers among T sticks, you should see the answer is (T+N-1)!/(T!(N-1)!). However, our N natural numbers are restricted to [0, base) and so there will be fewer possibilities. I want to find a simple formula for this case as well. The first thing I considered was deducting the number of possibilities where 'base' of the sticks had been replaced with a 'big stick'. Unfortunately, some possibilities are double counted because they have multiple places a 'big stick' could be inserted. Any ideas?
0
0
0
0
1
0
I need to write a program to analyze the performance of computer systems and networks using queuing theory (http://en.wikipedia.org/wiki/Queueing_theory). I was wondering if there is an open source Java library implementing the various algorithms of queuing theory that can make my task easier. Does anyone have any recommendations?
0
0
0
0
1
0
Possible Duplicates: Ints and Doubles doing division 1/252 = 0 in c#? Hi, Maybe because it's Friday, but I cannot understand this: (Double)1/2 = 0.5 (Double)1/(Double)2 = 0.5 (Double)((Double)1/(Double)2) = 0.5 (Double)(1/2) = 0.0 Why the last operation is 0? :S Kind regards.
0
0
0
0
1
0
I have a method that converts an int to a base60 string (using 0-9, a-z, and A-Z chars), but can't work out how to convert it back again. Here is my method for converting base10 to base60: public static function toBase60(value:Number):String { var targetBase:uint = 60; value = value.toString().split('.')[0]; var digits:Array = new Array(); while (value > 0) { digits.push(baseChars[value % targetBase]); value = Math.floor(value / targetBase); } var myResult:String = digits.reverse().join(''); return myResult; } Works well. But how do I get the base60 string back into a base10 int? I happen to be using ActionScript 3, but really, examples in any programming language, generic explanations or sudo code would be great.
0
0
0
0
1
0
I currently have an array full of data which from what I believe is the Amplitude of my wave file. It is currently at a low -32768 and at a high 32767. I also have the SampleRate which was 16,000hz. My understanding of sound isn't very good; does anyone know from this how I can calculate the Frequency? Help greatly appreciated, Monkeyguy.
0
0
0
0
1
0
What tools or web services are available for machine text translation. For example ENGLISH TEXT > SERVER or LIB > GERMAN TEXT Libraries are also acceptable. Is Google language API the only one ?
0
1
0
1
0
0
To make matter more specific: How to detect people names (seems like simple case of named entity extraction?) How to detect addresses: my best guess - find postcode (regexes); country and town names and take some text around them. As for phones, emails - they could be probably caught by various regexes + preprocessing Don't care about education/working experience at this point Reasoning: In order to build a fulltext index on resumes all vulnerable information should be stripped out from them. P.S. any 3rd party APIs/services won't do as a solution.
0
0
0
1
0
0
Stack Overflow implemented its "Related Questions" feature by taking the title of the current question being asked and removing from it the 10,000 most common English words according to Google. The remaining words are then submitted as a fulltext search to find related questions. How do I get such a list of the most common English words? Or most common words in other languages? Is this something I can just get off the Google website?
0
1
0
0
0
0
I am trying to translate a function in a book into code, using MATLAB and C#. I am first trying to get the function to work properly in MATLAB. Here are the instructions: The variables are: xt and m can be ignored. zMax = Maximum Sensor Range (100) zkt = Sensor Measurement (49) zkt* = What sensor measurement should have been (50) oHit = Std Deviation of my measurement (5) I have written the first formula, N(zkt;zkt*,oHit) in MATLAB as this: hitProbabilty = (1/sqrt( 2*pi * (oHit^2) ))... * exp(-0.5 * (((zkt- zktStar) ^ 2) / (oHit^2)) ); This gives me the Gaussian curve I expect. I have an issue with the definite integral below, I do not understand how to turn this into a real number, because I get horrible values out my code, which is this: func = @(x) hitProbabilty * zkt * x; normaliser = quad(func, 0, max) ^ -1; hitProbabilty = normaliser * hitProbabilty; Can someone help me with this integral? It is supposed to normalize my curve, but it just goes crazy.... (I am doing this for zkt 0:1:100, with everything else the same, and graphing the probability it should output.)
0
0
0
0
1
0
Okay so I have defined my DSNavigationManager class and it has a property called DSNavigationManagerStyle managerStyle: typedef enum { DSNavigationManagerStyleNone = 0, DSNavigationManagerStyleDefaultNavigationBar = 1 << 0, DSNavigationManagerStyleDefaultToolBar = 1 << 1, DSNavigationManagerStyleDefault = DSNavigationManagerStyleDefaultNavigationBar + DSNavigationManagerStyleDefaultToolBar, DSNavigationManagerStyleInteractiveNavigationBar = 1 << 2, DSNavigationManagerStyleInteractiveToolBar = 1 << 3, DSNavigationManagerStyleInteractiveWithDarkPanel = 1 << 4, DSNavigationManagerStyleInteractiveWithBackButton = 1 << 5, DSNavigationManagerStyleInteractiveWithTitleBar = 1 << 6, DSNavigationManagerStyleInteractiveDefault = DSNavigationManagerStyleInteractiveNavigationBar + DSNavigationManagerStyleInteractiveToolBar + DSNavigationManagerStyleInteractiveWithDarkPanel + DSNavigationManagerStyleInteractiveWithBackButton + DSNavigationManagerStyleInteractiveWithTitleBar, } DSNavigationManagerStyle; I just learned how to use bit-wise shifting but I don't know how to receive this information. I want to do something a little like: DSNavigationManagerStyle managerStyle = DSNavigationManagerStyleDefault; if(managerStyle "Has The DefaultNavigationBar bit or the DefaultToolBarBit") { // Implement } else { if(managerStyle "Has the InteractiveNavigationBar bit") { // Implement } if(managerStyle "Has the InteractiveToolBar bit") { // Implement } //.... and so on so that technically the object can implement all // styles, no styles, or any number of styles in between }
0
0
0
0
1
0
Is there a formula without if/else/switch/? etc that could replace the solution[,] matrix and what are the implications or differences on performance/efficiency for that? class Program { private static Random r = new Random(); // names of the "moves" private static string[] rps = { "PAPER", "ROCK", "SCISSORS"}; // result feedback string to be formatted private static string[] feedback = { "{1} Beats {0}, You Loose!","{0} Equals {1}, Draw!", "{0} Beats {1}, You Win!" }; // solution matrix ( 0 = loose ; 1 = draw ; 2 = win // array1: for paper; array2: for rock; array3: for scissors; ) private static int[,] solution = {{1, 2, 0},{0, 1, 2},{2, 0, 1}}; /// <summary> /// Rock Paper scissors solution w/o calculation or if/case/else/ /// </summary> /// <param name="args">dummy.</param> static void Main(string[] args) { // simulate the players move int player = r.Next(3); // simulate the computers move int computer = r.Next(3); // retrieve the result from the matrix int result = solution[player, computer]; //write the result of the match Console.WriteLine(String.Format("you : {0} vs {1} : computer", rps[player], rps[computer])); Console.WriteLine(String.Format(feedback[result], rps[player], rps[computer])); } }
0
0
0
0
1
0
I'm using the GNU GSL to do some matrix calculations. I'm trying to multiply a matrix B with the inverse of a matrix A. Now I've noticed that the BLAS-part of GSL has a function to do this, but only if A is triangular. Is there a specific reason to this? Also, what would be the fastest way to do this computation? Should I invert A using LU decomposition, or is there a better way? FWIW, A has the form P'GP, where P is a normal matrix, P' is its inverse, and G is a diagonal matrix. Thanks a bunch :)
0
0
0
0
1
0
I have three known 3-Dimensional points: A, B, and C. Addtionally, I have a fourth point, X. X lies on vector AB such that vector CX is perpendicular to vector AB. So AB · CX = 0 How do I find the unit vector of CX? The use-case here is that I am constructing a (translated) rotational matrix, where the origin is A, the z-axis passes through B, the xz-plane passes thtough C, and the axes are orthogonal I also have a vector object that provides dot and cross product functions at my disposal.
0
0
0
0
1
0
I am using a book with a function I would like to use. However I don't think I am getting the correct values from my function. Here is the instruction from the book: Here is the function as I have created it in MATLAB: function [ shortProbability ] = pShort( zkt, zktStar, short) if zkt > zktStar shortProbability = 0; else normalizer = 1/(1-exp(-short*zktStar)); shortProbability = normalizer * (short * exp(-short*zkt)); end end The values I am plugging in are: zkt = 0:1:100 zktStar = 50; short = 0.01; However my graph doesn't behave like the one which I am supposed to end up with, which is this: I am getting this from the graph, which looks correct, however I don't think it is being normalized properly: Can anyone help me to correct this function?
0
0
0
0
1
0
I have to answer this question that seems a riddle ... I don't know if there's a real solution or it's impossible... Questions : Having two double values, one is the total amount of money in the safe, the other is threshold of maximum money recommended in the safe For example: recommended value of money (threshold) : $1,500 Total amount is a variable that is calculated every 5 seconds by a timer, in this timer tick event i have the value of the recommended value of money and the value of the total amount of money in the safe. At the timer tick event, I need to check if the value of total money is greater than recommended value, and show a notification to the user UI. But since the timer tick event happen every 5 seconds, I need to show a notification the first time that the total amount is greater than recommended amount, and every 50$ step of difference above the threshold. An example (every row of this example is a timer tick event) : Total : 1200$ − Recommended : 1500$ → No Notification Total : 1505$ − Recommended : 1500$ → Notification (first overcoming of threshold) Total : 1520$ − Recommended : 1500$ → No Notification Total : 1537$ − Recommended : 1500$ → No Notification Total : 1558$ − Recommended : 1500$ → Notification (first overcoming of 50$ step) Total : 1574$ − Recommended : 1500$ → No Notification Total : 1586$ − Recommended : 1500$ → No Notification Total : 1598$ − Recommended : 1500$ → No Notification Total : 1612$ − Recommended : 1500$ → Notification (second overcoming of 50$ step) Total : 1623$ − Recommended : 1500$ → No Notification And so on. Is there a way (math calculation or algorithm) to show this notification knowing only this two value, without storing any other variable in memory ? I Can't store the "total amount" previous value in a variable. I don't know if there's a solution but someone have passed to me this question as a riddle. Do you have any idea if is there a solution to this question ?
0
0
0
0
1
0
So, I'm trying to figure out the total amount of return from an investment of £5 with a daily interest rate of 1.01%. Obviously, I am wanting the compound interest rate, so I have this so far: int main() { double i = 500; int loop; int loopa; double lowInterest; double highInterest; lowInterest = 1.01; highInterest = 1.75; cout.precision(2); for(loop = 1;loop < 1826;loop++) { if(i<1001) { i = i + ((i / 100) * lowInterest); } else { i = i + ((i / 100) * highInterest); } } cout << fixed << i << endl; return 0; } I am using 500 to represent the $5 just for personal preference. Am I doing this correctly? I get very strange results - 46592024576.00 for example - that make me think that somewhere I've made an error? Any suggestions?
0
0
0
0
1
0
I start using NaiveBayes/Simple classifier for classification (Weka), however I have some problems to understand while training the data. The data set I'm using is weather.nominal.arff. While I use use training test from the options, the classifier result is: Correctly Classified Instances 13 - 92.8571 % Incorrectly Classified Instances 1 - 7.1429 % a b classified as 9 0 a =yes 1 4 b = no My first question what should I understand from the incorrect classified instances? Why such a problem occurred? which attribute collection is classified incorrect? is there a way to understand this? Secondly, when I try the 10 fold cross validation, why I get different (less) correctly classified instances? The results are: Correctly Classified Instances 8 57.1429 % Incorrectly Classified Instances 6 42.8571 % a b <-- classified as 7 2 | a = yes 4 1 | b = no
0
0
0
1
0
0
I'm making a game where the player is an upright capped cylinder, and the world is axis aligned bounding boxes. Given this, how could I check if the cylinder is intersecting a box? Thanks
0
0
0
0
1
0
I'm trying to implement NegaMax for a game of checkers. I'm just testing it with a depth of 0 right now, meaning the current player just evaluates all his moves without regard to what the other player might do next. It works perfectly for about half the game (computes the scores correctly), and then part way through it starts spitting out non-sense answers. For example, White might have 1 piece left, and Black will have 5, but it will evaluate White's moves as a score of 7 for example, when they should all be negative because he's losing. Black might about to win on his next move, but it will evaluate the winning move as a -4 even though it should be 1000. I can understand it consistently outputting garbage, but why would it work for the first few turns and then start messing up? private static Move GetBestMove(Color color, Board board, int depth) { var bestMoves = new List<Move>(); IEnumerable<Move> validMoves = board.GetValidMoves(color); int highestScore = int.MinValue; Board boardAfterMove; int tmpScore; var rand = new Random(); Debug.WriteLine("{0}'s Moves:", color); foreach (Move move in validMoves) { boardAfterMove = board.Clone().ApplyMove(move); if (move.IsJump && !move.IsCrowned && boardAfterMove.GetJumps(color).Any()) tmpScore = NegaMax(color, boardAfterMove, depth); else tmpScore = -NegaMax(Board.Opposite(color), boardAfterMove, depth); Debug.WriteLine("{0}: {1}", move, tmpScore); if (tmpScore > highestScore) { bestMoves.Clear(); bestMoves.Add(move); highestScore = tmpScore; } else if (tmpScore == highestScore) { bestMoves.Add(move); } } return bestMoves[rand.Next(bestMoves.Count)]; } private static int NegaMax(Color color, Board board, int depth) { return BoardScore(color, board); } private static int BoardScore(Color color, Board board) { if (!board.GetValidMoves(color).Any()) return -1000; return board.OfType<Checker>().Sum(c => (c.Color == color ? 1 : -1) * (c.Class == Class.Man ? 2 : 3)); } I've isolated a board state that it doesn't like, on a 6x6 board: . . . . w B W . . . . . . w . . . W w = white, b = black, capital letter = king It appears that this is not a time or number-of-moves played issue, it just doesn't like particular board states. I don't see anything peculiar about this state though. In this state, it evaluates all 4 of Black's moves as -13. If you look at how I did the scoring, it says 2 pts per man, 3 pts per king, negative if owned by the other player. It looks as though it is treating all the pieces as white...that's the only way to get 13. I found another clue. In the board score method I got it to print what it's seeing.. this is what it's telling me: 2: White 4: White 6: White 13: White 17: White Where the board squares are numbered like this: 00 01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 I think it is indeed saying the black piece is white...... now to figure out what's causing this. So... now I know that the color is wrong, but only to the BoardScore function. My normal display routine never picked up on this otherwise I would have figured out the problem hours ago. I'm thinking it might be in the ApplyMove function that the color gets switched.. public Board ApplyMove(Move m) { if (m.IsJump) { bool indented = m.Start % Width < _rowWidth; int offset = indented ? 1 : 0; int enemy = (m.Start + m.End) / 2 + offset; this[m.Color, enemy] = Tile.Empty; } this[m.Color, m.End] = this[m.Color, m.Start]; this[m.Color, m.Start] = Tile.Empty; var checker = this[m.Color, m.End] as Checker; if (m.IsCrowned) checker.Class = Class.King; return this; } But that doesn't make a lot of sense either... the piece is just copied from the start position to the end position. Need to investigate what m.Color is... perhaps it'll provide more clues! I feel like a detective.
0
1
0
0
0
0
It's for a game of checkers. See revision history for older versions of code. private static Move GetBestMove(Color color, Board board, int depth) { var bestMoves = new List<Move>(); var validMoves = board.GetValidMoves(color); int highestScore = int.MinValue; Board boardAfterMove; int tmpScore; var rand = new Random(); Debug.WriteLine("{0}'s Moves:", color); foreach (var move in validMoves) { boardAfterMove = board.Clone().ApplyMove(move); if(move.IsJump && !move.IsCrowned && boardAfterMove.GetJumps(color).Any()) tmpScore = NegaMax(color, boardAfterMove, depth); else tmpScore = -NegaMax(Board.Opposite(color), boardAfterMove, depth); Debug.WriteLine("{0}: {1}", move, tmpScore); if (tmpScore > highestScore) { bestMoves.Clear(); bestMoves.Add(move); highestScore = tmpScore; } else if (tmpScore == highestScore) { bestMoves.Add(move); } } return bestMoves[rand.Next(bestMoves.Count)]; } private static int NegaMax(Color color, Board board, int depth) { var validMoves = board.GetValidMoves(color); int highestScore = int.MinValue; Board boardAfterMove; if (depth <= 0 || !validMoves.Any()) return BoardScore(color, board); foreach (var move in validMoves) { boardAfterMove = board.Clone().ApplyMove(move); if(move.IsJump && !move.IsCrowned && boardAfterMove.GetJumps(color).Any()) highestScore = Math.Max(highestScore, NegaMax(color, boardAfterMove, depth)); else highestScore = Math.Max(highestScore, -NegaMax(Board.Opposite(color), boardAfterMove, depth - 1)); } return highestScore; } private static int BoardScore(Color color, Board board) { if (!board.GetValidMoves(color).Any()) return -1000; return board.OfType<Checker>().Sum(c => (c.Color == color ? 1 : -1) * (c.Class == Class.Man ? 2 : 3)); } I'm trying it with depth 0, and the scores are correct for about half the game, and then all of a sudden it starts screwing up. One of the players will start proclaiming his score is higher than it really is. Why would it only work for half a game?!
0
1
0
0
0
0
What is the state of the art of algorithms to play the game of Go ? Which articles (describing algorithms) are best to read ? There is a StackExachge site devoted to Go, but not enough people commited to ask the question there.
0
1
0
0
0
0
Is it important for developers to know discrete math? Most of the books about algorithms and analysis have at least some references to math. I can easily understand the algorithms in principle and can implement them without any problem, but when it comes to the math parts I get stuck. Is it generally assumed that developers will have deep knowledge of math to understand algorithms and methods?
0
0
0
0
1
0
I wrote this simple code in python to calculate a given number of primes. The question I want to ask is whether or not it's possible for me to write a script that calculates how long it will take, in terms of processor cycles, to execute this? If yes then how? primes = [2] pstep = 3 count = 1 def ifprime (a): """ Checking if the passed number is prime or not""" global primes for check in primes: if (a%check) == 0: return False return True while 1000000000>= count: if ifprime(pstep): primes.append (pstep) print pstep count += 1 pstep += 1 The interesting thing about this problem is that whether or not I find primes after x cycles of incrementation is something nearly impossible to predict. Moreover, there's recursion happening in this scenario since the larger 'prime' list grow the longer it will take to execute this function. Any tips?
0
0
0
0
1
0
I am rotating an image around it center point but need to track a location on the image as it rotates. Given: Origin at 0,0 Image width and height of 100, 100 Rotation point at C(50,50) Angle of "a" (say 90 degrees in this example) Point P starts at (25,25) and after the rotation it is at Pnew(75,25) I haven't touched trig in 20 years but guessing the formula is simple...
0
0
0
0
1
0