Stack overflow on recursive function - function

got a Problem with recursive funktions. I made this one in java, that is just pretty basic, but doesn't work tho, due to an Stack overflow error. I mean what this function does is to open the funktion just as often as the size of the difference between a given number and the number you declare in the main funktion, what should really not be a problem for the stack, but well, doen't work the whole time, or whats the mistake here...?
thanks for the answers in advance :)
public class Übung_Baeume {
static int anzAufrufe=0;
static int zahl=23;
public static int zaehleAufrufe(int uebergabe)
{
anzAufrufe++;
if (uebergabe==zahl){
return anzAufrufe;
}
return zaehleAufrufe(uebergabe-1) +
zaehleAufrufe(uebergabe+1);
}
public static void main(String[] args) {
System.out.println(zaehleAufrufe(40));
}
}

ubergabe if not equal to 23 will recurse with ubergabe +1 and unbergabe - 1. Now each of those will do the same so you can just try this out:
zaehleAufrufe(40) ; ==>
zaehleAufrufe(39) + zaehleAufrufe(41) ; ==> neither of these are 23
zaehleAufrufe(38) + zaehleAufrufe(40) + zaehleAufrufe(40) + zaehleAufrufe(42)
Notice that last one.. Even though some of these eventually will hit a base case you see that you on the 3. expansion have 2 zaehleAufrufe(40). Each one of these expands like the above turning also into two zaehleAufrufe(40) and no one of these will even hit a base case.
For recursion to work you need to become simpler problems and in fact yours become several of the same amount and thus infinite recursion.
To open a function as many times as the difference you only recurse once:
public static int zaehleAufrufe(int uebergabe)
{
anzAufrufe++;
if (uebergabe <= zahl) {
return anzAufrufe;
}
return zaehleAufrufe(uebergabe-1);
}
zaehleAufrufe(40) ; ==>
zaehleAufrufe(39) ; ==>
...
zaehleAufrufe(23) ; ==> 18

This almost always means that nothing can stop the recursion from going deeper and deeper. There is no condition that stops when a certain level is reached whether the goal is achieved or not.
In your code you start from 40 and will stop only when you get to 23. But one of your branches is increasing the number:
return zaehleAufrufe(uebergabe-1) + zaehleAufrufe(uebergabe+1);
and will never go down to 23.
Welcome to StackOverflow with a stack overflow :)
P.S. The best thing to do is to reconsider your algorythm. If in a case you are sure you want to use a recursion, but it's branching is unpredictable due to depending on unknown data, you can put a level-limiting value. It is a dirty hack but there are cases when it is useful.
It is importaint to say that with this limit your code will still fail
- it will try to call this function as much as 2^33 times = about 8 billion, which is big enough :)
public class Übung_Baeume {
static int anzAufrufe=0;
static int zahl=23;
static int max_level = 32;
static bool fault = 0;
public static int zaehleAufrufe(int uebergabe, int level)
{
if(level == max_level)
{
fault = 1;
return 0;
}
anzAufrufe++;
if (uebergabe==zahl){
return anzAufrufe;
}
return zaehleAufrufe(uebergabe-1, level+1) +
zaehleAufrufe(uebergabe+1, level+1);
}
public static void main(String[] args) {
int ret = zaehleAufrufe(40,0);
if(fault == 0)
System.out.println(ret);
else
System.out.println("Fault - recursion level limit reached!");
}
}

Related

Cannot invoke mult(float) on the primitive type float

I'm working on a simple gravity program in Processing. My program takes particles and attracts them to each other based on the formula for gravity. Unfortunately, once I try to multiply the force to the direction with PVector.mult(), I get the error in the title:
Cannot invoke mult(float) on the primitive type float.
Here is my code for the method. G is defined elsewhere.
public float distance(Particle other) {
return location.sub(other.location).mag();
}
public PVector direction(Particle other) {
return location.sub(other.location).normalize();
}
public void gravity(Particle other) {
float grav = (G*((mass * other.mass)/pow(distance(other), 2)));
if(distance(other) != 0) {
acceleration.add(distance(other).mult(grav));
}
Why am I not able to pass a float where a float is due?
Let's take this line apart and split it into multiple steps:
acceleration.add(distance(other).mult(grav));
Here's my attempt to split it into multiple lines:
float grav = 42;
float distanceFromOther = distance(other);
float multipliedValue = distanceFromOther.mult(grav);
acceleration.add(multipliedValue);
Hopefully this makes it more obvious what's going on: you're trying to call mult() on a float value, which won't work. You need to call mult on a PVector or another class that contains a mult() function.

Collision bit reaches its maximum value while Initialization in LIBGDX

I am using Category_bits for detecting collision in LIBGDX. I have used all the values ranging from 0 to 16384 . Since we have to use the power of 2 while initializing the values, I have exceeded the limit and I am not able to initialize any bits anymore. The range for short_ bit is 0 to 16384 and if I use the next multiple of that number, after type casting it to a short value, the Category_bits doesn't detect collision between objects. Nothing happens when the object collides when I set the value greater than 16384.
Here is how I initialize the values,
public static final short x = 0;
public static final short y = 1;
public static final short z = 2;
public static final short a = 4;
public static final short b = 8;
public static final short c = 16;
.....
public static final short d = 16384;
public static final short e = (short) 32768; // exceeded the limit so type casted the number to short
When I type cast and use it, nothing collision detection happens. I have to detect collision in many things in my game so I need the solution to get rid of this problem. Please help. Thanks in advance.
I would strongly advise re-checking over your code and decide whether you actually need that many different categories. Even if you have that many different types of objects I suspect you could group together those which have the same collision filters into just one bit, you can then use other ways of identifying which "type" of entity is involved in a collision.
If you do really need to use that many different objects then the Box2d World class has a method setContactFilter(ContactFilter filter) which will allow you to specify a custom ContactFilter. This contains a shouldCollide(Fixture a, Fixture b) which returns true if a and b should collide and vice versa.
short also worked for me with minus numbers, because it reaches from -32768 till 32767 so you can also use
-32678, -16384 and so on.
I don't know how to use the contact filters, but I work with UserData which also works pretty good for me.
when you create your body I wrote something like this:
b2body.createFixture(fdef).setUserData("something");
and in my collision detection I used something like this:
public class WorldContactListener implements ContactListener{
#Override
public void beginContact(Contact contact) {
Fixture fixA = contact.getFixtureA();
Fixture fixB = contact.getFixtureB();
int cdef = fixA.getFilterData().categoryBits | fixB.getFilterData().categoryBits;
switch(cdef) {
case BreedingSeason.HERO_BIT | BreedingSeason.TRAMPOLIN_BIT:
if(fixA.getUserData() == "somethingElse" && fixB.getUserData() == "something") {
...
} else if(fixB.getUserData() == "somethingElse" && fixA.getUserData() == "something") {
...
}
break;
}
and don't forget the break after each case in the switch ;)
i hope this helps you

Pointer to a function with Android

I have a problem to solve with Android, but it's really confusing.
Using the function below:
function accumulate(combiner, nullValue, list){
if(list.length == 0){
return nullValue;
}
var first = list.removeFirst();
return combiner(first, accumulate(combiner, nullValue, list));
}
Develop the function sumOfSquares which returns the sum of squares of a list (Example: 1² + 2² + 3²...)
sumOfSquares([1,2,3,4,5])
returns the number 55.
In this case, the function accumulate must be used. The variable "combiner" is a "pointer to a function". The implementation of the function "combiner" is part of the solution.
I have no problem with the basics, doing the sum of squares, etc, but the part "pointer to a function" really confused me.
If anyone can tell me which is the way to get to the answer, I will be thankful :)
I have done until the code below:
public class MainActivity extends Activity{
protected void onCreate(...){
....
List<Integer> list = new ArrayList<Integer>();
//Fill the list with values
long value = accumulate(sumOfSquares(list), 0, list);
//Show the value
}
private int sumOfSquares(List<Integer> list){
int sum = 0;
for(int i = 0; i < list.size(); i++){
sum += Math.pow(list.get(i), 2);
}
return sum;
}
private long accumulate(int combiner, long nullValue, List<Integer> list){
if(list.size() == 0){
return nullValue;
}
int first = list.get(0);
list.remove(0);
return combiner(first, accumulate(combiner, nullValue, list));
}
private long combiner(int first, int rest){
return first + rest;
}
}
In some languages, the notion of a pointer to a function makes sense, and you could write the code pretty much as you've given it in the example. Not in Java, though, which is what underlies Android. (Android is a bit of a weird choice for this, by the way...)
What you want to do in Java (without giving you the whole solution) is to define a
private int combiner(int first, int rest);
method that takes the first element of the list and the solution to the smaller problem defined by the rest of the list, and produces the answer from these two bits. In other words, if first is the first element, and rest is the sum of the squares of everything except the first element, what is the sum of the squares of the whole list (in terms of first and rest)?
Now your accumulate method does almost exactly what you've written out. It just removes the first element, recursively calls itself on the rest of the list, and returns the value of combining the first element with the result of the recursive call.
The nullValue is there to give you the sum of the squares of an empty list.
If you want to look up more of the details of the theory, you're basically doing functional programming but in an imperative language :)

Thrust - accessing neighbors

I would like to use Thrust's stream compaction functionality (copy_if) for distilling indices of elements from a vector if the elements adhere to a number of constraints. One of these constraints depends on the values of neighboring elements (8 in 2D and 26 in 3D). My question is: how can I obtain the neighbors of an element in Thrust?
The function call operator of the functor for the 'copy_if' basically looks like:
__host__ __device__ bool operator()(float x) {
bool mark = x < 0.0f;
if (mark) {
if (left neighbor of x > 1.0f) return false;
if (right neighbor of x > 1.0f) return false;
if (top neighbor of x > 1.0f) return false;
//etc.
}
return mark;
}
Currently I use a work-around by first launching a CUDA kernel (in which it is easy to access neighbors) to appropriately mark the elements. After that, I pass the marked elements to Thrust's copy_if to distill the indices of the marked elements.
I came across counting_iterator as a sort of substitute for directly using threadIdx and blockIdx to acquire the index of the processed element. I tried the solution below, but when compiling it, it gives me a "/usr/include/cuda/thrust/detail/device/cuda/copy_if.inl(151): Error: Unaligned memory accesses not supported". As far as I know I'm not trying to access memory in an unaligned fashion. Anybody knows what's going on and/or how to fix this?
struct IsEmpty2 {
float* xi;
IsEmpty2(float* pXi) { xi = pXi; }
__host__ __device__ bool operator()(thrust::tuple<float, int> t) {
bool mark = thrust::get<0>(t) < -0.01f;
if (mark) {
int countindex = thrust::get<1>(t);
if (xi[countindex] > 1.01f) return false;
//etc.
}
return mark;
}
};
thrust::copy_if(indices.begin(),
indices.end(),
thrust::make_zip_iterator(thrust::make_tuple(xi, thrust::counting_iterator<int>())),
indicesEmptied.begin(),
IsEmpty2(rawXi));
#phoad: you're right about the shared mem, it struck me after I already posted my reply, subsequently thinking that the cache probably will help me. But you beat me with your quick response. The if-statement however is executed in less than 5% of all cases, so either using shared mem or relying on the cache will probably have negligible impact on performance.
Tuples only support 10 values, so that would mean I would require tuples of tuples for the 26 values in the 3D case. Working with tuples and zip_iterator was already quite cumbersome, so I'll pass for this option (also from a code readability stand point). I tried your suggestion by directly using threadIdx.x etc. in the device function, but Thrust doesn't like that. I seem to be getting some unexplainable results and sometimes I end up with an Thrust error. The following program for example generates a 'thrust::system::system_error' with an 'unspecified launch failure', although it first correctly prints "Processing 10" to "Processing 41":
struct printf_functor {
__host__ __device__ void operator()(int e) {
printf("Processing %d\n", threadIdx.x);
}
};
int main() {
thrust::device_vector<int> dVec(32);
for (int i = 0; i < 32; ++i)
dVec[i] = i + 10;
thrust::for_each(dVec.begin(), dVec.end(), printf_functor());
return 0;
}
Same applies to printing blockIdx.x Printing blockDim.x however generates no error. I was hoping for a clean solution, but I guess I am stuck with my current work-around solution.

Without using recursion how can a stack overflow exception be thrown?

Without using recursion how can a stack overflow exception be thrown?
Since no one else has mentioned it:
throw new System.StackOverflowException();
You might do this when testing or doing fault-injection.
Declare an ENORMOUS array as a local variable.
If you call enough methods, a stack overflow can occur anytime. Although, if you get stack overflow errors without using recursion, you may want to rethink how you're doing things. It's just so easy with recursion because in an infinite loop, you call a ton of methods.
The following applies to Windows, but most OSs implement this in a similar fashion.
The short answer is: if you touch the last guard page, it will throw.
An exception of type EXCEPTION_STACK_OVERFLOW (C00000FD) is raised when your application touches the bottom page of the stack, that is marked a PAGE_GUARD protection flag, and there is no room to grow the stack (commit one more page), see How to trap stack overflow in a Visual C++ application.
The typical case when this happens is when the stack has grown as the result of many function frames on the stack (ie. out of control recursion), as the result of fewer frames but very large frame sizes (functions with a very large local scoped object) or by explicitly allocating from the stack with _alloca.
Another way to cause the exception is to simply intentionally touch the guard page, eg. by dereferencing a pointer that points into that page. This can happen due to a variable initializion bug.
Stack overflows can occur on valid execution paths if the input causes a very deep nesting level. For instance see Stack overflow occurs when you run a query that contains a large number of arguments inside an IN or a NOT IN clause in SQL Server.
Every method call that has not yet returned consumes some stack space. (Methods with more local variables consume more space.) A very deep call stack can result in stack overflow.
Note that on systems with limited memory (mobile devices and such) you don't have much stack space and will run out sooner.
Short answer: if you have an object which calls an internal object, you increase the stack trace by 1. So, if you have 1000s of objects nested inside one another, each calling its internal object, eventually you'll get a stack overflow.
Here's a demonstration of how to generate primes using nested iterators:
using System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
Program p = new Program();
IEnumerator<int> primes = p.AllPrimes().GetEnumerator();
int numberOfPrimes = 1000;
for (int i = 0; i <= numberOfPrimes; i++)
{
primes.MoveNext();
if (i % 1000 == 0)
{
Console.WriteLine(primes.Current);
}
}
Console.ReadKey(true);
}
IEnumerable<int> FilterDivisors(IEnumerator<int> seq, int num)
{
while (true)
{
int current = seq.Current;
if (current % num != 0)
{
yield return current;
}
seq.MoveNext();
}
}
IEnumerable<int> AllIntegers()
{
int i = 2;
while (true)
{
yield return i++;
}
}
IEnumerable<int> AllPrimes()
{
IEnumerator<int> nums = AllIntegers().GetEnumerator();
while (true)
{
nums.MoveNext();
int prime = nums.Current;
yield return prime;
// nested iterator makes a big boom
nums = FilterDivisors(nums, prime).GetEnumerator();
}
}
}
}
There's no recursion, but the program will throw a stack overflow exception after around 150,000 primes.
If you're talking about C++ with a reasonable standard library, I image that this would work:
while (true) {
alloca(1024 * 1024); // arbitrary - 1M per iteration.
}
Details on alloca.
int main()
{
//something on the stack
int foo = 0;
for (
//pointer to an address on the stack
int* p = &foo;
//forever
;
//ever lower on the stack (assuming that the stack grows downwards)
--p)
{
//write to the stack
*p = 42;
}
}
You can allocate a few bytes in the stack as well.
static void Main(string[] args)
{
Span<byte> b = stackalloc byte[1024 * 1024 * 1024]; // Process is terminating due to StackOverflowException.
}
Easiest way to make a StackOverflowException is the following:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
SomeClass instance = new SomeClass();
string name = instance.Name;
}
}
public class SomeClass
{
public string Name
{
get
{
return Name;
}
}
}
}