Rigueur mathématique, une idée ?
Salut !
Je n'avais jamais vraiment réalisé à quel point la précision des nombres en JavaScript était... étrange. Il parait qu'ils sont codés / stockés sur 64 bits, ce qui devrait nous donner une certaine précision dans leur manipulation, alors j'imaginais que, par exemple 0.01 + 0.06 donnerait 0.07. Mais... non ! :aie: Bref, je vous laisse faire le test pour connaître ce résultat merveilleux.
Passons aux choses sérieuses. En dessous je vous glisse le code d'une petite classe utilitaire. Avec, vous pourrez essayer l'instruction suivante, qui donne un résultat fort intéressant aussi.
Code:
1 2 3
| with(Coordinates) {
convert(convert([1,1], SPHERICAL), SPHERICAL, CARTESIAN);
} |
On pourrait s'attendre à retrouver [1, 1] mais... que neni ! :aie:
Si d'aventure un expert des chiffres venait à passer par là, ou n'importe qui ayant une idée pertinente en fait...
Code:
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 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68
| Coordinates = {
CARTESIAN: 0x01,
SPHERICAL: 0x02,
/** Converts some coordinates from one system to another. */
convert: function(coordinates, context, target) {
// Only the target might be defined. In that case, it is passed as the first parameter.
if(!target) {
if(!context) {
throw new Error("Targeted space required.");
}
target = context;
context = Coordinates.CARTESIAN;
}
var result = null;
if(target != context) {
// Working with 3 dimensions.
while(coordinates.length < 3) {
coordinates.push(0);
}
switch(context) {
case Coordinates.CARTESIAN:
switch(target) {
case Coordinates.SPHERICAL:
with(Math) {
var x = coordinates[0];
var y = coordinates[1];
var z = coordinates[2];
var rho = sqrt(pow(x, 2) + pow(y, 2) + pow(z, 2));
var phi = acos(z / rho) || 0;
var theta = acos(x / sqrt(pow(x, 2) + pow(y, 2))) || 0;
if(y < 0) {
theta = 2 * PI - theta;
}
result = [rho, phi, theta];
}
break;
}
break;
case Coordinates.SPHERICAL:
switch(target) {
case Coordinates.CARTESIAN:
with(Math) {
var rho = coordinates[0];
var phi = coordinates[1];
var theta = coordinates[2];
var x = rho * sin(phi) * cos(theta);
var y = rho * sin(phi) * sin(theta);
var z = rho * cos(phi);
result = [x, y, z];
}
break;
}
break;
}
}
else {
throw new Error("Conversion is to be made between two diferent spaces.");
}
return result;
}
} |