Cannot invoke mult(float) on the primitive type float - parameter-passing

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.

Related

Libgdx- Resetting a Vector3 to use it multiple times in different situations

OK guys I need your help,
I'm trying to figure out how to reset a Vector3, to use it on multiple situations,...
For example I got a code where for testing purpose I have several buttons,
Where the first one uses a Matrix4 that refers to a Vector3 to translate a player,
How would I go to do so:
Button 1 pressed
Vector3: 1,2,3
Button 2 pressed
Vector3: reset, new values 2,4,6
Pseudo code for comprehension..
Can't seem to find a correct way to do so,
Not behind the computer right now,
Code will come in time,
Maybe if else if can do the trick but not sure :3
Any hint?
for reference, edited qn:
stage.addActor(tpS);
ghost = new Matrix4();
tpIleApprentis.addListener((new InputListener() {
#Override
public boolean touchDown(InputEvent event, float x, float y, int pointer, int button) {
TpS.hide();
translation = new Vector3(86.83f,96f,63.5f);
ghost.getTranslation(translation);
translation.set(0,0,0);
PlayerSystem.characterComponent.ghostObject.setWorldTransform(ghost);
return false;
}
}));
Ok so,
as I was working with Ashley ECS and Bullet System,
I finally ended up using such method that basically remove the player and recreate the player,
Yes the solution isn't optimal, but it works,
Actually it's plenty sufficient:
tpIleApprentis0.addListener(new InputListener() {
#Override
public boolean touchDown(InputEvent event, float x, float y, int pointer, int button) {
gameWorld.remove(gameWorld.character);
gameWorld.remove(gameWorld.characterHair);
gameWorld.remove(gameWorld.characterEar);
gameWorld.remove(gameWorld.characterScar);
gameWorld.remove(gameWorld.characterMouth);
System.out.println("Teleportation Ville des Apprentis");
gameWorld.createPlayer(86.8f,64.4f,-96.6f);
return false;
}
});
Ashley engine is created and located in gameworld class;
remove method is part of ashley ecs system and involves bullet component
for the create method it's the same:
public void remove(Entity entity)
{
engine.removeEntity(entity);
bulletSystem.removeBody(entity);
}
public void createPlayer(float x, float y, float z)
{
character = playerFactory.createMaleCharacter(bulletSystem, x, y, z);
characterHair = playerFactory.createMaleHair(x, y, z);
characterEar = playerFactory.createMaleEar(x, y, z);
characterMouth = playerFactory.createMaleMouth(x, y, z);
characterScar = playerFactory.createMaleScar(x, y, z);
engine.addEntity(character);
engine.addEntity(characterHair);
engine.addEntity(characterEar);
engine.addEntity(characterMouth);
engine.addEntity(characterScar);
...
if anybody got a better solution?
but as said, actually this solution fits my needs
You don't need to "reset" the Vector3 before reusing it, you can simply override it with new values using one of the set methods.
https://libgdx.badlogicgames.com/ci/nightlies/docs/api/com/badlogic/gdx/math/Vector3.html#set-float-float-float-
Vector3 vector = new Vector3(1, 2, 3);
...
vector.set(2, 4, 6); // reuse

Explanation to why two constructors are required

Unfortunately, I do not feel confident with my understanding of default constructors.
I have searched extensively to find a resource that provides an explanation to adhere to my personal learning curve of the Java language. However, upon completing an assignment, I feel I may not be meeting the assignment criteria due to my own feeling of redundancy to need for a default constructor. This is why i feel like i am misinterpreting the concept of different types of constructors all together.
I have created two constructors as the assignment requires. One that takes in no parameters and initializes instance variables to a default value. And another that takes in parameters to give values to the object variables when the new object is created in the main method.
Why am I creating a default constructor for the object if the default is never used in the main method? Below is a sample of my code:
public class Circle {
private double x; // declaring variable to hold value of x coordinate
private double y; // Variable to hold value of y coordinate
private double r; // Variable to hold value of the radius of a circle
/* default constructor */
Circle() {
x = 0.0;
y = 0.0;
r = 0.0;
}
/* constructor takes in three parameters and sets values for variables x, y, and r */
public Circle(double x, double y, double r) {
this.x = x;
this.y = y;
this.r = r;
}
// test class created for main method
public class TestCircle {
public static void main (String[] args){
Circle c1 = new Circle(2.0,3.0,9.0);
System.out.println();
System.out.println(" A circle object has been created with the following attributes:");
c1.printAttributes();
System.out.println();
System.out.println("The circle is tested for the maximum radius of 8.0...");
c1.setRadius(8.0);
System.out.println();
System.out.println("... since the radius is more than the allowable maximum, the new attributes for the Circle are:");
c1.printAttributes();
System.out.println();
System.out.println("The area of the Circle is " + c1.area());
System.out.println("The Circumference of the circle is " + c1.circumference());
System.out.println();
System.out.println("The origin of the circle is now moved by a specified amount...");
c1.move(6,-7);
System.out.println();
System.out.println("The new attributes of the circle are:");
c1.printAttributes();
System.out.println();
System.out.println("Testing if the point (10,-20) is inside the circle...");
System.out.println();
if (c1.isInside(10,-20)){
System.out.println("The point (10,-20) is inside the circle");
}
else {
System.out.println("The point (10,-20) is not inside the circle");
}
} // end of main
} // end of class
If you don’t use it you should delete it. Sometimes you will need to create empty objects in order to set attributes a posteriori, but if you are not using it at all there is no point to have it
The point of making default constructors is sometimes for back end stuff and is considered a "good programming practice" no you don't use the default constructor here in your main and in fact your code would run just fine with no default constructor comment it out and re run your tester you will see it works fine.

Stack overflow on recursive 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!");
}
}

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 :)

Does this higher order function have a name?

I see this pattern everywhere in my code, and in libraries, yet there appears to be no name or abstraction of it that I can find anywhere.
Example (pseudocode)
T foo( T x, void f(T&) )
{
T y = x;
f( y );
return y;
}
Basically: Take a value, and a function that transforms that value. Make of a copy of the value, transform it, and return it.
Real-life examples (C++)
T operator+(const T& x, const T& y)
{
T z = x; // Make a copy
operator+=(z, y); // Modify in place
return z;
}
Vector3 Vector3::normalized() const
{
Vector3 x = *this; // Make a copy
x.normalize(); // Modify in place
return x;
}
T sorted(T const& x)
{
T y = x; // Make a copy (yeah, yeah, could have passed by value)
sort( y ); // Modify in place
return y;
}
Basically, you have an in place function (with side-effects) and make an out-of-place function (without side-effects) out of it.
Is there a name for this pattern? Do you know of any libraries or languages that use it? Obviously functional languages won't use it because they don't have referentially opaque functions to begin with.
It's actually what in mathematics and FP is called a composition, because you could express it as mystery_function(x, fun) = fun(copy(x)) instead.
In Design Patterns linguo, it's a wrapper, that wraps the function call with a copy. So I would rather naturally call it a copy wrapper. But I never saw it classified anywhere.