Club Delphi  
    Paypal   FTP   CCD     Buscar   Trucos   Trabajo   Foros

Retroceder   Foros Club Delphi > Principal > Varios
Registrarse FAQ Miembros Calendario Guía de estilo Temas de Hoy

Coloboración Paypal con ClubDelphi

Respuesta
 
Herramientas Buscar en Tema Desplegado
  #1  
Antiguo 06-03-2007
Mick Mick is offline
Miembro
 
Registrado: may 2003
Posts: 405
Poder: 24
Mick Va por buen camino
Metodos y funciones para generar numeros aleatorios hay infinitos, y cualquiera se puede inventar una nuevo algoritmo para generarlos.

En tu caso solo veo dos opciones:

- Preguntar a microsoft por el algoritmo que usan ellos, veo dificil que te respondan pero bueno.

- Si las semillas a utilizar son pocas, asi como la lista de valores es pequeña, usando el programa original generar una tabla con la lista de valores posibles que generan todas las posibles semillas y utilizar esa tabla en el programa en delphi, en definitiva tener precalculados todos los posibles resultados.

Es mas estos numeros precalculados los utilizaria incluso en el programa original, es una locura generar numeros aleatorios y cruzar los dedos para que siga funcionando bien el sistema todos los dias, ese programa estaria jugando a la ruleta rusa, hoy fallara hoy no fallara ? Hoy decidira microsoft en alguna actualizacion mejorar la libreria de generacion de numeros cambiando el algoritmo y me mandara a la mierda el funcionamiento del programa que tengo instalado en cientos de clientes, si no es hoy sera mañana, dentro de un mes ? Lo siento, pero quien decidio usar ese sistema realmente le quedo la cabeza descansada !!!!!!!!!!

Saludos

Última edición por Mick fecha: 06-03-2007 a las 23:25:14.
Responder Con Cita
  #2  
Antiguo 07-03-2007
Avatar de mamcx
mamcx mamcx is offline
Moderador
 
Registrado: sep 2004
Ubicación: Medellín - Colombia
Posts: 3.942
Poder: 28
mamcx Tiene un aura espectacularmamcx Tiene un aura espectacularmamcx Tiene un aura espectacular
No hay necesidad de preguntarle a MS.

El codigo desensamblado es mas o menos asi:

Código Delphi [-]
function Random.InternalSample: Integer;
begin
    index := self.inext;
    inextp := self.inextp;
    if (++index >= $38) then
        index := 1;
    if (++inextp >= $38) then
        inextp := 1;
    num := (self.SeedArray[index] - self.SeedArray[inextp]);
    if (num < 0) then
        inc(num, $7fffffff);
    self.SeedArray[index] := num;
    self.inext := index;
    self.inextp := inextp;
    begin
        Result := num;
        exit
    end
end;

function Random.Next(minValue: Integer; maxValue: Integer): Integer;
begin
    if (minValue > maxValue) then
        raise ArgumentOutOfRangeException.Create('minValue', string.Format(CultureInfo.CurrentCulture, Environment.GetResourceString('Argument_MinMaxValue'), New(array[2] of TObject, ( ( 'minValue', 'maxValue' ) ))));
    num := (maxValue - minValue);
    if (num <= $7fffffff) then
        begin
            Result := (((self.Sample * num) as Integer) + minValue);
            exit
        end;
    begin
        Result := ((((self.GetSampleForLargeRange * num) as Int64) as Integer) + minValue);
        exit
    end
end;

function Random.Next: Integer;
begin
    Result := self.InternalSample
end;

function Random.Sample: Double;
begin
    Result := (self.InternalSample * 4.6566128752457969E-10)
end;

function Random.GetSampleForLargeRange: Double;
begin
    num := self.InternalSample;
    if ( {pseudo} (if ((self.InternalSample mod 2) = 0) then 1 else 0) <> 0) then
        num := -num;
    num2 := num;
    inc(num2, 2147483646);
    begin
        Result := (num2 div 4294967293);
        exit
    end
end

NOTA: Es solo una porcion y el desemsamblaje no es perfecto.

Ahora, para una mejor aproximacion quizas el codigo de MONO nos sirva:

Código:
	public class Random
	{
		const int MBIG = int.MaxValue;
		const int MSEED = 161803398;
		const int MZ = 0;

		int inext, inextp;
		int [] SeedArray = new int [56];
		
		public Random ()
			: this (Environment.TickCount)
		{
		}

		public Random (int Seed)
		{
			int ii;
			int mj, mk;

			// Numerical Recipes in C online @ http://www.library.cornell.edu/nr/bookcpdf/c7-1.pdf
			mj = MSEED - Math.Abs (Seed);
			SeedArray [55] = mj;
			mk = 1;
			for (int i = 1; i < 55; i++) {  //  [1, 55] is special (Knuth)
				ii = (21 * i) % 55;
				SeedArray [ii] = mk;
				mk = mj - mk;
				if (mk < 0)
					mk += MBIG;
				mj = SeedArray [ii];
			}
			for (int k = 1; k < 5; k++) {
				for (int i = 1; i < 56; i++) {
					SeedArray [i] -= SeedArray [1 + (i + 30) % 55];
					if (SeedArray [i] < 0)
						SeedArray [i] += MBIG;
				}
			}
			inext = 0;
			inextp = 31;
		}

		protected virtual double Sample ()
		{
			int retVal;

			if (++inext  >= 56) inext  = 1;
			if (++inextp >= 56) inextp = 1;

			retVal = SeedArray [inext] - SeedArray [inextp];

			if (retVal < 0)
				retVal += MBIG;

			SeedArray [inext] = retVal;

			return retVal * (1.0 / MBIG);
		}

		public virtual int Next ()
		{
			return (int)(Sample () * int.MaxValue);
		}

		public virtual int Next (int maxValue)
		{
			if (maxValue < 0)
				throw new ArgumentOutOfRangeException(Locale.GetText (
					"Max value is less then min value."));

			return (int)(Sample () * maxValue);
		}

		public virtual int Next (int minValue, int maxValue)
		{
			if (minValue > maxValue)
				throw new ArgumentOutOfRangeException (Locale.GetText (
					"Min value is greater then max value."));

			uint diff = (uint)(maxValue - minValue);
			if (diff == 0)
				return minValue;

			int result = (int)(Sample () * diff + minValue);
			return ((result != maxValue) ? result : (result - 1));
		}

		public virtual void NextBytes (byte [] buffer)
		{
			if (buffer == null)
				throw new ArgumentNullException ("buffer");

			for (int i = 0; i < buffer.Length; i++) {
				buffer [i] = (byte)(Sample () * (byte.MaxValue + 1)); 
			}
		}

		public virtual double NextDouble ()
		{
			return this.Sample ();
		}
	}
Otra solucion seria crear una DLL en Delphi que haga el codigo de random e invocar desde VB.NET con PInvoke, asi se garantizaria una unica implementacion.
__________________
El malabarista.

Última edición por mamcx fecha: 07-03-2007 a las 16:59:13.
Responder Con Cita
Respuesta



Normas de Publicación
no Puedes crear nuevos temas
no Puedes responder a temas
no Puedes adjuntar archivos
no Puedes editar tus mensajes

El código vB está habilitado
Las caritas están habilitado
Código [IMG] está habilitado
Código HTML está deshabilitado
Saltar a Foro

Temas Similares
Tema Autor Foro Respuestas Último mensaje
Aprender a ser como tu enemigo DarkByte Debates 3 26-05-2004 19:43:50


La franja horaria es GMT +2. Ahora son las 22:00:18.


Powered by vBulletin® Version 3.6.8
Copyright ©2000 - 2026, Jelsoft Enterprises Ltd.
Traducción al castellano por el equipo de moderadores del Club Delphi
Copyright 1996-2007 Club Delphi