Agradeceré a quien me solucione un problemilla JAVA

Tengo que entregarlo antes de 16 horas.


/**
* Main class of the Java program.
*
*/

public class Main {

    public static void main(String[] args) {
        double[] preyPredLV;
        double[] preyPred;                  //Double array contains initial pop. Hares preyPred[0] and pop Lynx preyPred[1]
       
        double[] a =new double[2];          //Double Array contains constants a1 and a2
        double[] b =new double[2];          //Double Array contains constants b1 and b2
        int n= 10;                          //Integer, Number of desired periods
        double iniLynxPob= 20;              //Initial Declaration Population Lynxs (double)
        double iniHarePob= 300;             //Initial Declaration Population Hares (double)
       
   
        double a1= 0.1;     //Real value of a1, coef.growth of hares in absence of lynx
        double a2= 0.01;    //Real value of a2, coef.loss of hares due pred by lynx
        double b1= 0.01;    //Real value of b1, coef.loss of lynx in absence of hares
        double b2= 0.00002; //Real value of b2, coef.growth of lynx pred hares
       
        a[0]=a1;            //Saving a1 value to array a[0]
        a[1]=a2;            //Saving a2 value to array a[1]
        b[0]=b1;            //Saving b1 value to array b[0]
        b[1]=b2;            //Saving b2 value to array b[1]
       
       
       
        System.out.println(a[0]);
        System.out.println(a[1]);
        System.out.println(b[0]);
        System.out.println(b[1]);
        System.out.println(n);
        System.out.println(iniLynxPob);
        System.out.println(iniHarePob);
    }


Esto es lo que llevo hecho, no consigo hacerme a la sintaxis de java, si el programa lo hiciese con un automata podria hacerlo en cuestion de segundos (a fin de cuentas es aplicar un par de formulas con diferentes valores durante un numero determinado de ciclos y actualizarlos en cada ciclo).



El problema en si es este:

The dynamics between predators and preys in a given ecosystem attracts a lot of attention from researchers. Different scientists have developed Predator-Prey models to try to understand the interactions and foresee the evolution of the populations.

One of the first analyzed Predator-Prey ecosystems was the "Lynx - Snowshoe hare" and one of the first Predator-Prey models defined was the one developed by Lotka and Volterra.

This Predator-Prey model defines:
* H[n] as the snowshoe hare population (being n a specific moment of time)
* L[n] as the lynx population
* It assumes that the primary growth of the hare population in the absence of lynx is a1*H[n] and that the lynx population in the absence of hares declines -b1*L[n]
* It also assumes that the primary loss of snowshoe hares is due to predating -a2*H[n]*L[n] and the growth of the lynx population is from the energy derived from eating snowshoe hares b2*H[n]*L[n]

The Lotka-Volterra model is defined by the following formula:
H[n+1] = H[n] + a1 * H[n] - a2*H[n]*L[n] = H[n] * (1 + a1 - a2*L[n])
L[n+1] = L[n] - b1 * L[n] + b2*H[n]*L[n] = L[n] * (1 - b1 +b2*H[n])



For instance, let’s assume that the initial population of snowshoe hares is 300 and the initial population of lynxes is 20, and the values of the constants that regulate the model are a1 = 0.1, a2 = 0.01, b1 = 0.01 and b2 = 0.00002. The previous formula can be used to calculate the population of both lynxes and snowshoe hares after 2 periods:

After 1 period the population of snowshoe hares will be:
H[1] = H[0] + a1 * H[0] - a2*H[0]*L[0] = H[0] * (1 + a1 - a2*L[0]) = 300 *(1 + 0.1 - 0.01*20) = 270
In turn, the population of lynxes will be:
L[1] = L[0] - b1 * L[0] + b2*H[0]*L[0] = L[0] * (1 - b1 +b2*H[0]) = 20 * (1 - 0.01 + 0.00002*300) = 19.92

Notice that we keep the decimals for the following loop in the formula.
After 2 periods, the population of snowshoe hares will be:
H[2] = H[1] * (1 + a1 - a2*L[1]) = 270 * (1 + 0.1 - 0.01*19,92) = 243.216
And the population of lynxes will be:
L[2] = L[1] * (1 - b1 +b2*H[1]) = 19.92 * (1 - 0.01 + 0.00002*270) = 19.828368

or even after 200 periods:
H[200] = 903.17 snowshoe hares
L[200] = 3.91 lynxes
-----------------------------------------------------------------------------------------------------------------------------------
The goal of this activity is to: SOLVE THIS PROBLEM PROGRAMMING AN ITERATIVE METHOD
-----------------------------------------------------------------------------------------------------------------------------------
Guidelines for solving the problem:
1) The header of the method should be:
● double[] preyPredLV(double[] preyPred, double[] a, double[] b, int n)
2) The method should have as arguments:
● An array called "preyPred" with 2 doubles:
○ The initial population of snowshoe hares, preyPred[0];
○ The initial population of lynx, preyPred[1]
● An array called "a" with 2 doubles containing the constants a1 and a2:
○ a[0] = a1;
○ a[1] = a2;
● An array called "b" with 2 doubles containing the constants b1 and b2:
○ b[0] = b1;
○ b[1] = b2;
● The number of periods, "n", at which we want to predict the future population of snowshoe hares and lynxes.
3) The method should return the array "preyPred", in a way that it should contain:
● The population of snowshoe hares at the given number of periods "n" (H[n]) in preyPred[0];
● The population of lynxes at the given number of periods "n" (L[n]) in preyPred[1].
4) You can choose to solve this problem using one of the following two possibilities:
● To implement an iterative method with a for loop; or
● To implement an iterative method with a while loop
To check your solution you can use the data from the example.
IMPORTANT: Do not forget to comment your code properly, including Javadoc comments so that your peers can better understand it.
Editado por VozdeLosMuertos. Razón: Ofrecer invitaciones
Summon @Cp3 [hallow]

Nah ahora en sirio summon @Lazeru
a, b, a1, a2...

Los nombres de las variables deben ser descriptivos, no poner lo primero que te salga por el teclado.
Lo importante es que vaya a 1080p y 60fps.
A mí, a mí!! porfa forocarros es la ilusión de mi vida!!!!
Que le den a foropaletos. xD
Liquid Snake yo escribió:Summon @Cp3 [hallow]

Nah ahora en sirio summon @Lazeru

Me da palo y estoy a reventar de trabajo [buuuaaaa]
Con más tiempo si lo haría, pero con 16h...
amchacon escribió:a, b, a1, a2...

Los nombres de las variables deben ser descriptivos, no poner lo primero que te salga por el teclado.


Lo se, el programilla es para un curso que estoy haciendo.

Por lo que tengo que usar lo que me dan, normalmente en las variables intento (de hecho, si te fijas, en las variables que he ido creando yo, son mas descriptivas "iniHaresPop", iniLyxnPop, etc.
El código es una marranada, y eso que tienes en el enunciado un important . Aunque sea el código que te han dado, si lo arreglas primero luego lo tendrás más claro y más facil.

Pero vamos, es crear unos vectores y meterlos en un bucle e iterar la fórmula

Me cuesta creer que puedas programarlo en un automata y aquí no, máxime cuando es un código mucho más fácilmente programable en AWL o ST que en contactos.
@eduy1985 Es un ejercicio de Java? o es un ejercicio de Sistemas Dinámicos?

Es simplemente resolver las ecuaciones de Volterra, para lo cual puedes usar un esquema explícito de Euler, o FTCS.

Edito: Vale. Te dan la fórmula y parece que les importa poco que la entiendas. Es un Euler con dt=1
jorcoval escribió:El código es una marranada, y eso que tienes en el enunciado un important

Pero vamos, es crear unos vectores y meterlos en un bucle e iterar la fórmula

Me cuesta creer que puedas programarlo en un automata y aquí no, máxime cuando es un código mucho más fácilmente programable en AWL o ST que en contactos.


Jorcoval, lo que me refiero es que a nivel de sintaxis de java, cometo muchos errores. Usar un contador, con varios bloques de operaciones matematicas es sencillo sabiendo como se usa el lenguaje del automata en cuestion, el problema es que yo de java...todavia estoy pegado.

Moki_X escribió:@eduy1985 Es un ejercicio de Java? o es un ejercicio de Sistemas Dinámicos?

Es simplemente resolver las ecuaciones de Volterra, para lo cual puedes usar un esquema explícito de Euler, o FTCS.


Si, si simplemente es aplicar la formula que tengo en negrita, un numero N de veces, para obtener la poblacion final, con los valores de las constantes que tambien nos dan.

El problema es que
Guidelines for solving the problem:
1) The header of the method should be:
● double[] preyPredLV(double[] preyPred, double[] a, double[] b, int n)
2) The method should have as arguments:
● An array called "preyPred" with 2 doubles:
○ The initial population of snowshoe hares, preyPred[0];
○ The initial population of lynx, preyPred[1]
● An array called "a" with 2 doubles containing the constants a1 and a2:
○ a[0] = a1;
○ a[1] = a2;
● An array called "b" with 2 doubles containing the constants b1 and b2:
○ b[0] = b1;
○ b[1] = b2;
● The number of periods, "n", at which we want to predict the future population of snowshoe hares and lynxes.
3) The method should return the array "preyPred", in a way that it should contain:
● The population of snowshoe hares at the given number of periods "n" (H[n]) in preyPred[0];
● The population of lynxes at the given number of periods "n" (L[n]) in preyPred[1].
4) You can choose to solve this problem using one of the following two possibilities:
● To implement an iterative method with a for loop; or
● To implement an iterative method with a while loop
To check your solution you can use the data from the example.
IMPORTANT: Do not forget to comment your code properly, including Javadoc comments so that your peers can better understand it.

Hay va la solución. Solo tienes que pasarlo a lenguaje java.
Es que das poco tiempo para hacerlo despues de llegar a casa después de pasarme el día programando un SCADA, siento no poder ayudar mucho más.

Primero, lo que haría es una limpieza del código: Aunque sea lo que te han dado, poner nombres claros a las variables ya te ayudará mucho.

Luego es crearte los vectores a recorrer dentro de un bucle (para que te hagas a la idea, el bucle principal seria el bloque OB1 de siemens, aunque parará de iterar al cumplirse las condiciones apropiadas)
Ese bucle actualiza valores según la formula en negrita. Hay que tener cuidado pues el valor de iteracion (normalmente i) debe estar entre 0 y n-1 (donde n es el tamaño de vector).
Hay que controlarlo porque java es menos robusto que los lenguajes de automata, que normalmente tragan con excederse el valor de vector, aunque el resultado, obviamente, no será el esperado.
jorcoval escribió:Es que das poco tiempo para hacerlo despues de llegar a casa después de pasarme el día programando un SCADA, siento no poder ayudar mucho más.

Primero, lo que haría es una limpieza del código: Aunque sea lo que te han dado, poner nombres claros a las variables ya te ayudará mucho.

Luego es crearte los vectores a recorrer dentro de un bucle (para que te hagas a la idea, el bucle principal seria el bloque OB1 de siemens, aunque parará de iterar al cumplirse las condiciones apropiadas)
Ese bucle actualiza valores según la formula en negrita. Hay que tener cuidado pues el valor de iteracion (normalmente i) debe estar entre 0 y n-1 (donde n es el tamaño de vector).
Hay que controlarlo porque java es menos robusto que los lenguajes de automata, que normalmente tragan con excederse el valor de vector, aunque el resultado, obviamente, no será el esperado.




Gracias Jorcoval, descansa, y gracias de nuevo. Voy a pegarme un rato, voy a asignar nombres descriptivos a las variables, lo unico que espero que el codigo no me de errores al compilar (por ejemplo, no se a que te refieres con el important), todavia estoy verde con la sintaxis y las reglas.
/**
* Main class of the Java program.
*
*/

public class Main {

    public static void main(String[] args) {
        double[] preyPredLV;
        double[] preyPred;                  //Double array contains initial pop. Hares preyPred[0] and pop Lynx preyPred[1]
       
        double[] a =new double[2];          //Double Array contains constants a1 and a2
        double[] b =new double[2];          //Double Array contains constants b1 and b2
        int n= 200;                          //Integer, Number of desired periods
        double[] L=new double[300];              //Initial Declaration Population Lynxs (double)
        double[] H=new double[300];             //Initial Declaration Population Hares (double)
      L[0]=20.0;   // Inicializacion de poblacion Linx
      H[0]=300.0;    // Inicializacion de poblacion Hires
       
   
        double a1= 0.1;     //Real value of a1, coef.growth of hares in absence of lynx
        double a2= 0.01;    //Real value of a2, coef.loss of hares due pred by lynx
        double b1= 0.01;    //Real value of b1, coef.loss of lynx in absence of hares
        double b2= 0.00002; //Real value of b2, coef.growth of lynx pred hares
       
        a[0]=a1;            //Saving a1 value to array a[0]
        a[1]=a2;            //Saving a2 value to array a[1]
        b[0]=b1;            //Saving b1 value to array b[0]
        b[1]=b2;            //Saving b2 value to array b[1]
      
      //Bucle for para calcular la progresion de las poblaciones segun los coeficientes. Itera 200 veces.
      
      for(int i=0; i<n; i++){
        H[i+1] = H[i] * (1.0 + a1 - a2*L[i]);
      L[i+1] = L[i] * (1 - b1 +b2*H[i]);
        }
       
      //Se muesta el estado de la poblacion habiendo iterado 200 veces.

        System.out.println(H[200]);
        System.out.println(L[200]);
    }}


De nada.
Si representas las H frente a n, deberías obtener algo como esto:

Imagen
Se me ha adelantado Black29, pero he aquí otra:

import java.lang.Integer;

public class PredatorPreySolver
{

    double[] preyPredLV(double[] preyPred, double[] a, double[] b, int n)
    {
        double[] H; // Prey population
        double[] L; // Predator population
        int i = 1;

        n = n + 1;
       
        H = new double[n];
        L = new double[n];

        H[0] = preyPred[0];
        L[0] = preyPred[1];

        // System.out.println(String.format("H[%s] [%s] L[%s] [%s]", 0, H[0], 0, L[0]));

        for ( ; i < n ; i++ )
        {
            H[i] = H[i - 1] * ( 1.0 + a[0] - ( a[1] * L[i - 1] ) );
            L[i] = L[i - 1] * ( 1.0 - b[0] + ( b[1] * H[i - 1] ) );
           
            // System.out.println(String.format("H[%s] = %s * ( 1.0 + %s - ( %s * %s ) )", i, H[i-1], a[0], a[1], L[i-1]));
            // System.out.println(String.format("L[%s] = %s * ( 1.0 - %s + ( %s * %s ) )", i, L[i-1], b[0], b[1], H[i-1]));
        }

        return new double[]{ H[i - 1], L[i - 1] };
    }

    public static void main(String[] args)
    {
        int n = Integer.parseInt(args[0]);

        double[] values = (new PredatorPreySolver()).preyPredLV(
            new double[]{ 300.0, 20.0 },
            new double[]{ 0.1, 0.01 },
            new double[]{ 0.01, 0.00002 },
            n);

        System.out.println(String.format("Snowshoe hares [%s]", values[0]));
        System.out.println(String.format("Lynxes [%s]", values[1]));
    }

}


¿"Syntax Highlighter" para cuando?

EDIT: ¿Podrías poner la versión en autómata que dices? ¿Está hecha con Prolog?
https://www.youtube.com/watch?v=KEkrWRHCDQU

Aquí tienes un tutorial.
De como hackear el tiempo y volver al pasado XD, lo siento por la broma tonta
@Mithrandir0x Me he adelantado porque lo he hecho en plan choricillo xDDDD SI lo hubiera limpiado como tu me dan las 2 de la mañana xDD que tengo Java oxidadisimo.
Mithrandir0x escribió:Se me ha adelantado Black29, pero he aquí otra:

import java.lang.Integer;

public class PredatorPreySolver
{

    double[] preyPredLV(double[] preyPred, double[] a, double[] b, int n)
    {
        double[] H; // Prey population
        double[] L; // Predator population
        int i = 1;

        n = n + 1;
       
        H = new double[n];
        L = new double[n];

        H[0] = preyPred[0];
        L[0] = preyPred[1];

        // System.out.println(String.format("H[%s] [%s] L[%s] [%s]", 0, H[0], 0, L[0]));

        for ( ; i < n ; i++ )
        {
            H[i] = H[i - 1] * ( 1.0 + a[0] - ( a[1] * L[i - 1] ) );
            L[i] = L[i - 1] * ( 1.0 - b[0] + ( b[1] * H[i - 1] ) );
           
            // System.out.println(String.format("H[%s] = %s * ( 1.0 + %s - ( %s * %s ) )", i, H[i-1], a[0], a[1], L[i-1]));
            // System.out.println(String.format("L[%s] = %s * ( 1.0 - %s + ( %s * %s ) )", i, L[i-1], b[0], b[1], H[i-1]));
        }

        return new double[]{ H[i - 1], L[i - 1] };
    }

    public static void main(String[] args)
    {
        int n = Integer.parseInt(args[0]);

        double[] values = (new PredatorPreySolver()).preyPredLV(
            new double[]{ 300.0, 20.0 },
            new double[]{ 0.1, 0.01 },
            new double[]{ 0.01, 0.00002 },
            n);

        System.out.println(String.format("Snowshoe hares [%s]", values[0]));
        System.out.println(String.format("Lynxes [%s]", values[1]));
    }

}


¿"Syntax Highlighter" para cuando?

EDIT: ¿Podrías poner la versión en autómata que dices? ¿Está hecha con Prolog?





Gracias! La verdad es que en este portatil ahora mismo no tengo ningun programa (bueno, si, el tia portal) para hacer el "problema", pero te lo puedo dibujar en papel, basicamente, seria lo mismo, aunque jorcoval seguro que me saca varios errores gordos si lo hago de cabeza.




santousen escribió:https://www.youtube.com/watch?v=KEkrWRHCDQU

Aquí tienes un tutorial.
De como hackear el tiempo y volver al pasado XD, lo siento por la broma tonta


Lo triste es que hace 3 dias estaba a las 5 de la mañana viendo Kung Fury
como odio java... rage a tope XD
22 respuestas