Anda di halaman 1dari 14

Math.

random()
La llamada a Math.random() devuelve un nmero aleatorio entre 0.0 y 1.0, excluido este ltimo valor, es decir, puede devolver 0.346442, 0.2344234, 0.98345,.... En muchas de nuestras aplicaciones no nos servir este rango de valores. Por ejemplo, si queremos simular una tirada de dado, queremos nmeros entre 1 y 6 sin decimales. Debemos echar unas cuentas para obtener lo deseado. En primer lugar, miramos cuntos valores queremos. En nuestro caso del dado son 6 valores, del 1 al 6 ambos incluido. Debemos entonces multiplicar Math.random() por 6 (que es (maximo-minimimo)+1, es decir, (6-1)+1)
Math.random()*6 // Esto da valores de 0.0 a 6.0, excluido el 6.0

Como nuestro primer valor es 1, le sumamos 1 al resultado


Math.random()*6 + 1 // Esto da valores entre 1.0 y 7.0 excluido el 7.0

Finalmente, para conseguir un entero, quitamos los decimales usando la clase Math.floor()
int valorDado = Math.floor(Math.random()*6+1);

En general, para conseguir un nmero entero entre M y N con M menor que N, debemos usar esta frmula
int valorEntero = Math.floor(Math.random()*(N-M+1)+M); y N, ambos incluidos. // Valor entre M

Si no queremos un valor entero sino double, la frmula es sin el +1


double valorAleatorio = Math.random()*(N-M)+M;

eso s, recuerda que el valor N queda excluido y no saldr nunca.

Clase java.util.Random
La clase java.util.Random debemos instanciarla, a diferencia del mtodo Math.random(). A cambio, tendremos bastantes ms posibilidades. Podemos usar un constructor sin parmetros o bien pasarle una semilla. Si instanciamos varias veces la clase con la misma semilla, tendremos siempre la misma secuencia de nmeros aleatorios.
Random r1 = new Random(); Random r2 = new Random(4234); Random r3 = new Random(4234); // r2 y r3 darn la misma secuencia.

Lo ms fcil es usar el constructor sin parmetros, que normalmente dar secuencias distintas en cada instancia. De todas formas, una manera de obtener una semilla que sea distinta cada vez que ejecutemos nuestro programa puede ser obtener el tiempo actual en milisegundos con System.currentTimeMillis(), que dar nmeros distintos salvo que hagamos la instacia justo en el mismo instante de tiempo. Con esta clase, una vez instanciada, nuestro problema del dado sera bastante ms sencillo, usando el mtodo nextInt(int n), que devuelve un valor entre 0 y n, excluido n
Random r = new Random(); int valorDado = r.nextInt(6)+1; // Entre 0 y 5, ms 1.

Generacin de nmeros aleatorios en Java


Podemos generar nmeros aleatorios en Java de dos formas distintas:

1. Utilizando el mtodo esttico random de la clase Math: Math.random() 2. Utilizando la clase Random

1. Generar nmeros aleatorios utilizando Math.random()

El mtodo random() de la clase Math devuelve un nmero al azar positivo de tipo double mayor o igual que 0.0 y menor que 1.0

Por ejemplo, el siguiente for genera 5 nmeros aleatorios

for(int i = 1; i<=5; i++) System.out.println(Math.random());

genera 5 nmeros aleatorios que podran ser estos:

0.6586423340678433 0.35474701449674206 0.9552201267900652

0.8309552833908893 0.05210677512170114

Para obtener un nmero entero entre 1 y un lmite N, hay que multiplicar el nmero aleatorio obtenido por N, sumarle 1 y convertirlo a entero:

(int)(Math.random()*N + 1);

Por ejemplo, para obtener 5 nmeros aleatorios enteros entre 1 y 6: for(int i = 1; i<=5; i++) System.out.println((int)(Math.random()*6 + 1));

Para obtener un nmero entero entre dos valores DESDE , HASTA, ambos incluidos, debemos usar la frmula: (int)(Math.random()*(HASTA-DESDE+1)+DESDE); Por ejemplo, para generar 5 nmeros enteros al azar entre 8 y 15:

for(int i = 1; i<=5; i++) System.out.println((int)(Math.random()*(15-8+1)+8));

2. Generar nmeros aleatorios utilizando la clase Random

La clase Random proporciona un generador de nmeros aleatorios ms flexible que el mtodo random de la clase Math anterior.

Se encuentra en el paquete java.util.

Para obtener un nmero aleatorio utilizando la clase Random debes seguir estos pasos:

1. Importar la clase: import java.util.Random;

2. Crear un objeto de la clase Random 3. Utilizar uno de los mtodos de la clase para obtener el nmero

Algunos mtodos de la clase Random:

nextInt() devuelve un nmero entero positivo o negativo dentro del rango de enteros.

nextInt(int n) devuelve un nmero entero >=0 y menor que n. nextDouble() Devuelve un nmero positivo de tipo double mayor o igual que 0.0 y menor que 1.0 Por ejemplo, para generar 5 enteros al azar:

Random rnd = new Random(); for(int i = 1; i<=5; i++) System.out.println(rnd.nextInt());

Un posible resultado de este for es:

-394395199 1133763686 -424454120 1147379979 -2049113297

Para generar 5 enteros entre 0 y 6:

for(int i = 1; i<=5; i++)

System.out.println(rnd.nextInt(7));

Para generar 5 enteros entre 1 y 6:

for(int i = 1; i<=5; i++) System.out.println(rnd.nextInt(6)+1);

En general, para generar enteros al azar entre dos lmites DESDE , HASTA, ambos incluidos: rnd.nextInt(HASTA-DESDE+1)+DESDE

Por ejemplo, para generar 5 nmeros aleatorios entre 10 y 20:

for(int i = 1; i<=5; i++) System.out.println(rnd.nextInt(20-10+1)+10);

Secuencias de nmeros aleatorios


En la siguiente porcin de cdigo, se imprime dos secuencias de cinco nmeros aleatorios uniformemente distribudos entre [0, 1), separando los nmeros de cada una de las secuencias por un carcter tabulador.
System.out.println("Primera secuencia"); for (int i = 0; i < 5; i++) { System.out.print("\t"+rnd.nextDouble()); } System.out.println(""); System.out.println("Segunda secuencia"); for (int i = 0; i < 5; i++) { System.out.print("\t"+rnd.nextDouble()); } System.out.println("");

Comprobaremos que los nmeros que aparecen en las dos secuencias son distintos.

En la siguiente porcin de cdigo, se imprime dos secuencias iguales de nmeros aleatorios uniformemente distribudos entre [0, 1). Se establece la semilla de los nmeros aleatorios con la funcin miembro setSeed.
rnd.setSeed(3816); System.out.println("Primera secuencia"); for (int i = 0; i < 5; i++) { System.out.print("\t"+rnd.nextDouble()); } System.out.println(""); rnd.setSeed(3816); System.out.println("Segunda secuencia"); for (int i = 0; i < 5; i++) { System.out.print("\t"+rnd.nextDouble()); } System.out.println(""); package azar; import java.util.Random; public class AzarApp { public static void main (String[] args) { int[] ndigitos = new int[10]; int n; Random rnd = new Random(); // Inicializar el array for (int i = 0; i < 10; i++) { ndigitos[i] = 0; } // verificar que los nmeros aleatorios estn uniformente distribudos for (long i=0; i < 100000L; i++) { // genera un nmero aleatorio entre 0 y 9 n = (int)(rnd.nextDouble() * 10.0); //Cuenta las veces que aparece un nmero ndigitos[n]++; } // imprime los resultados for (int i = 0; i < 10; i++) { System.out.println(i+": " + ndigitos[i]); } //Dos secuencias de 5 nmero (distinta semilla) System.out.println("Primera secuencia"); for (int i = 0; i < 5; i++) { System.out.print("\t"+rnd.nextDouble()); } System.out.println(""); System.out.println("Segunda secuencia"); for (int i = 0; i < 5; i++) { System.out.print("\t"+rnd.nextDouble());

} System.out.println(""); //Dos secuencias de 5 nmero (misma semilla) rnd.setSeed(3816L); System.out.println("Primera secuencia"); for (int i = 0; i < 5; i++) { System.out.print("\t"+rnd.nextDouble()); } System.out.println(""); rnd.setSeed(3816); System.out.println("Segunda secuencia"); for (int i = 0; i < 5; i++) { System.out.print("\t"+rnd.nextDouble()); } System.out.println(""); } }

matrices public class matrices { public static void main (String[] args) { int a=5,i,j; //declaras variables, en este caso a es el tamao de la matriz cuadrada int matriz[][]=new int[a][a]; // asi se declara una matriz for (i=0;i<a;i++) { for(j=0;j<a;j++) { matriz[i][j]=(int)(Math.random()*10); // Ingresa un numero aleatorio a la posicion [i][j] System.out.print(" "+matriz[i][j]); // Muestra el numero de la posicion [i][j] } System.out.println(); //Para bajar una linea (En la impresion) } } }

Hoy el programa completo para realizar operaciones de matrices como son la suma, resta, multiplicacion, transpuesta, determinante, inversa.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47

import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; /** * * @author paxx */ public class Matriz { static BufferedReader entrada =new BufferedReader(new InputStreamReader(System.in)); public static int opc, fila, colum, fila2, colum2; public static double [][] m1; public static double [][] m2; /** * @param args the command line arguments */ public static void main(String[] args) throws IOException { do { System.out.print("Opcionesn " ); System.out.print("1.- Introducir matriz A n " ); System.out.print("2.- Introducir matriz B n " ); System.out.print("3.- A + B n " ); System.out.print("4.- A - B n " ); System.out.print("5.- A * B n " ); System.out.print("6.- Det(A) n " ); System.out.print("7.- A ^ t n " ); System.out.print("8.- A ^ -1 n " ); System.out.print("0.- SALIR n " ); System.out.print("Elige una opcion " ); opc=Integer.parseInt( entrada.readLine()); switch(opc){ case 1: matriz1(); break; case 2: matriz2(); break; case 3: sumar(); break; case 4: restar(); break; case 5: multi(); break; case 6: deta(); break; case 7:traa(); break; case 8:inva(); break; } }while(opc!=0); } private static void sumar() throws IOException { if(fila==fila2 &amp;&amp; colum==colum2)

48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94

{ for( int x=0;x&lt;fila;x++) { for( int y=0;y&lt;colum;y++) { System.out.print((m1[x][y])+(m2[x][y])+" , "); } System.out.print("n"); } }else{ System.out.print("no se pude sumar las matrices " ); } } private static void matriz1() throws IOException { System.out.print("tamao de filas " ); fila=Integer.parseInt( entrada.readLine()); System.out.print("tamao de columnoas " ); colum=Integer.parseInt( entrada.readLine()); m1= new double [fila][colum]; for(int i=0;i&lt;fila;i++){ for(int j=0;j&lt;colum;j++){ System.out.print("valor de matriz en ["+(i+1)+" , "+(j+1)+" ]" ); m1[i][j]=Double.parseDouble( entrada.readLine()); } } } private static void matriz2() throws IOException { System.out.print("tamao de filas " ); fila2=Integer.parseInt( entrada.readLine()); System.out.print("tamao de columnoas " ); colum2=Integer.parseInt( entrada.readLine()); m2= new double [fila2][colum2]; for(int i=0;i&lt;fila2;i++){ for(int j=0;j&lt;colum2;j++){ System.out.print("valor de matriz en ["+i+1+" , "+(j+1)+" ]" ); m2[i][j]=Double.parseDouble( entrada.readLine()); } } } private static void sumar2() { if(fila==fila2 &amp;&amp; colum==colum2) { for( int x=0;x&lt;fila;x++) { for( int y=0;y&lt;colum;y++) { System.out.print((m1[x][y])+(m2[x][y])+" , "); }

95 96 97 98 99 100 101 102 103 104 105 106 107 108"); 109 110 111 112 113 114 115 116 117 118 119 120 121 122 "); 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141

System.out.print("n"); } }else{ System.out.print("no se pude sumar las matrices " ); } } private static void restar() { if(fila==fila2 &amp;&amp; colum==colum2) { for( int x=0;x&lt;fila;x++) { for( int y=0;y&lt;colum;y++) { System.out.print((m1[x][y])-(m2[x][y])+" , } System.out.print("n"); } }else{ System.out.print("no se pude restar las matrices " ); } } private static void restar2() { if(fila==fila2 &amp;&amp; colum==colum2) { for( int x=0;x&lt;fila;x++) { for( int y=0;y&lt;colum;y++) { System.out.print((m2[x][y])-(m1[x][y])+" , } System.out.print("n"); } }else{ System.out.print("no se pude sumar las matrices " ); } } private static void multi() throws IOException { if(colum==fila2) { double [][] r1=new double[fila][colum2]; for(int x=0;x&lt;fila;x++) { for(int y=0;y&lt;colum2;y++) { for(int m=0;m&lt;colum;m++) { r1[x][y]+=m1[x][m]*m2[m][y]; } System.out.print(r1[x][y]+" , "); }

System.out.print("n"); 142 } 143 }else{ 144 System.out.print("No se puede multiplicar matrices"); 145 String a=entrada.readLine(); } 146 } 147 148 private static void multi2() throws IOException { 149 if(colum2==fila) 150 { 151 double [][] r1=new double[fila2][colum]; for(int x=0;x&lt;fila2;x++) 152 { 153 for(int y=0;y&lt;colum;y++) 154 { 155 for(int m=0;m&lt;colum2;m++) { 156 r1[x][y]+=m2[x][m]*m1[m][y]; 157 } 158 System.out.print(r1[x][y]+" , "); 159 } 160 System.out.print("n"); } 161 }else{ 162 System.out.print("No se puede multiplicar matrices"); 163 String a=entrada.readLine(); 164 } 165 } 166 private static void deta() throws IOException { 167 if(fila==colum){ 168 System.out.print("La determinante es : 169"+determinante(m1)); 170 String a=entrada.readLine(); }else{ 171 System.out.print("La Matriz no tiene determinante"); 172 String a=entrada.readLine(); 173 } 174 } 175 176 public static double determinante(double[][] matriz){ double det; 177 if(matriz.length==2){ 178 det=(matriz[0][0]*matriz[1][1])179(matriz[1][0]*matriz[0][1]); 180 return det; } 181 double suma=0; 182 for(int i=0; i&lt;matriz.length; i++){ 183 double[][] nm=new double[matriz.length-1][matriz.length-1]; 184 for(int j=0; j&lt;matriz.length; j++){ 185 if(j!=i){ for(int k=1; k&lt;matriz.length; k++){ 186 int indice=-1; 187 if(j&lt;i) 188

indice=j; 189 else if(j&gt;i) 190 indice=j-1; 191 nm[indice][k-1]=matriz[j][k]; 192 } } 193 } 194 if(i%2==0) 195 suma+=matriz[i][0] * determinante(nm); 196 else 197 suma-=matriz[i][0] * determinante(nm); } 198 return suma; 199 } 200 201 private static void detb() throws IOException { 202 if(fila2==colum2){ System.out.print("La determinante es : 203 "+determinante(m2)); 204 String a=entrada.readLine(); 205 }else{ 206 System.out.print("La Matriz no tiene determinante"); 207 String a=entrada.readLine(); } 208 } 209 210 private static void traa() throws IOException { 211 System.out.print("La matriz original"); 212 System.out.print("n"); 213 for(int x=0;x&lt;fila;x++) { 214 for(int y=0;y&lt;colum;y++) 215 { 216 System.out.print(m1[x][y]+ " , "); 217 } System.out.print("n"); 218 } 219 System.out.print("nn"); 220 System.out.print("La matriz transpuesta"); 221 System.out.print("n"); 222 for(int x=0;x&lt;colum;x++) { 223 for(int y=0;y&lt;fila;y++) 224 { 225 System.out.print(m1[y][x]+ " , "); 226 } System.out.print("n"); 227 } 228 String a=entrada.readLine(); 229 } 230 231 private static void trab() throws IOException { 232 System.out.print("La matriz original"); System.out.print("n"); 233 for(int x=0;x&lt;fila2;x++) 234 { 235

236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282

for(int y=0;y&lt;colum2;y++) { System.out.print(m2[x][y]+ " , "); } System.out.print("n"); } System.out.print("nn"); System.out.print("La matriz transpuesta"); System.out.print("n"); for(int x=0;x&lt;colum2;x++) { for(int y=0;y&lt;fila2;y++) { System.out.print(m2[y][x]+ " , "); } System.out.print("n"); } String a=entrada.readLine(); } private static void inva() throws IOException { if(fila==colum &amp;&amp; determinante(m1)!=0){ double[][] res = matrizInversa(m1); for(int i=0;i&lt;res.length ; i++){ for(int j=0;j&lt;res.length;j++){ System.out.print( ((res[i][j]*100)/100)+" , "); } System.out.print("n"); } String a=entrada.readLine(); }else{ System.out.println("no tiene inversa"); String a=entrada.readLine(); } } private static void invb() throws IOException { if(fila2==colum2 &amp;&amp; determinante(m1)!=0){ double[][] res = matrizInversa(m2); for(int i=0;i&lt;res.length ; i++){ for(int j=0;j&lt;res.length;j++){ System.out.print(((res[i][j]*100)/100)+" , "); } System.out.print("n"); } String a=entrada.readLine(); }else{ System.out.println("La matriz no tiene inversa"); String a=entrada.readLine(); } } public static double[][] matrizInversa(double[][] matriz) { double det=1/determinante(matriz); double[][] nmatriz=matrizAdjunta(matriz); multiplicarMatriz(det,nmatriz);

return nmatriz; 283 } 284 285 public static void multiplicarMatriz(double n, double[][] matriz) { 286 for(int i=0;i&lt;matriz.length;i++) 287 for(int j=0;j&lt;matriz.length;j++) matriz[i][j]*=n; 288 } 289 290 public static double[][] matrizAdjunta(double [][] matriz){ 291 return matrizTranspuesta(matrizCofactores(matriz)); 292 } 293 294 public static double[][] matrizCofactores(double[][] matriz){ double[][] nm=new double[matriz.length][matriz.length]; 295 for(int i=0;i&lt;matriz.length;i++) { 296 for(int j=0;j&lt;matriz.length;j++) { 297 double[][] det=new double[matriz.length2981][matriz.length-1]; double detValor; 299 for(int k=0;k&lt;matriz.length;k++) { 300 if(k!=i) { 301 for(int l=0;l&lt;matriz.length;l++) { 302 if(l!=j) { 303 int indice1=k&lt;i ? k : k-1 ; int indice2=l&lt;j ? l : l-1 ; 304 det[indice1][indice2]=matriz[k][l]; 305 } 306 } 307 } 308 } detValor=determinante(det); 309 nm[i][j]=detValor * (double)Math.pow(-1, i+j+2); 310 } 311 } 312 return nm; } 313 314 public static double[][] matrizTranspuesta(double [][] matriz){ 315 double[][]nuevam=new double[matriz[0].length][matriz.length]; 316 for(int i=0; i&lt;matriz.length; i++){ 317 for(int j=0; j&lt;matriz.length; j++) 318 nuevam[i][j]=matriz[j][i]; } 319 return nuevam; 320 } 321 322}

Anda mungkin juga menyukai