By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
438,480 Members | 1,808 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 438,480 IT Pros & Developers. It's quick & easy.

degrees not radians

P: n/a
Is it possible to set the Math functions to use degrees instead of
radians?

I'm working out some astronomical calculations and everything is in
degrees. All those conversions are driving me a bit crazy!

Jeff
Jul 20 '05 #1
Share this Question
Share on Google+
20 Replies


P: n/a
"Jeff Thies" <no****@nospam.net> writes:
Is it possible to set the Math functions to use degrees instead of
radians?
I'm working out some astronomical calculations and everything is in
degrees. All those conversions are driving me a bit crazy!


Nope.

Do your conversion only at input and output, and store all your
intermediate results in radian measure.

You could define some helper functions. Note that I don't know
whether I've committed any sins of floating-point-misuse here.

// m is an angle measure in degrees
function radians(m) { return m * Math.PI / 180.0; }

// m is an angle measure in radians
function degrees(m) { return m * 180.0 / Math.PI; }

Then if you were really desperate you could define your own
variant functions:

// m is an angle measure in degrees
define cosD(m) { return Math.cos(radians(m)); }

but it is not a good idea to be constantly converting and back-
converting. Like I said, convert only at input and output.

--
Chris Jeris cj****@oinvzer.net Apply (1 6 2 4)(3 7) to domain to reply.
Jul 20 '05 #2

P: n/a
> Then if you were really desperate you could define your own
variant functions:

// m is an angle measure in degrees
define cosD(m) { return Math.cos(radians(m)); }
I like that idea but can't get it to work. I'm getting an error:

missing ; before statement. (after the define)

but it is not a good idea to be constantly converting and back-
converting. Like I said, convert only at input and output.
I wish! I'm not smart enough to do that! Ever look at the calculations for
the Moon's position? It's nothing I feel like tinkering with!

Cheers,
Jeff

--
Chris Jeris cj****@oinvzer.net Apply (1 6 2 4)(3 7) to domain to reply.

Jul 20 '05 #3

P: n/a
"Jeff Thies" <no****@nospam.net> writes:
// m is an angle measure in degrees
define cosD(m) { return Math.cos(radians(m)); }

I like that idea but can't get it to work. I'm getting an error:
missing ; before statement. (after the define)


This was me having a Scheme braino. Replace 'define' by 'function'.

--
Chris Jeris cj****@oinvzer.net Apply (1 6 2 4)(3 7) to domain to reply.
Jul 20 '05 #4

P: n/a
JRS: In article <uy***********@oinvzer.net>, seen in
news:comp.lang.javascript, Christopher Jeris <cj****@oinvzer.net> posted
at Thu, 18 Dec 2003 13:10:10 :-
You could define some helper functions. Note that I don't know
whether I've committed any sins of floating-point-misuse here.

// m is an angle measure in degrees
function radians(m) { return m * Math.PI / 180.0; } ...


Looks OK. If called a lot, it ***might*** be a little faster to do a
global var Pi = Math.PI and then use that. If, as is possible, 90
degrees is used a lot, then Pi2 = Pi/2 for a further small gain.

--
John Stockton, Surrey, UK. ?@merlyn.demon.co.uk Turnpike v4.00 IE 4
<URL:http://jibbering.com/faq/> Jim Ley's FAQ for news:comp.lang.javascript
<URL:http://www.merlyn.demon.co.uk/js-index.htm> jscr maths, dates, sources.
<URL:http://www.merlyn.demon.co.uk/> TP/BP/Delphi/jscr/&c, FAQ items, links.
Jul 20 '05 #5

P: n/a
"Jeff Thies" <no****@nospam.net> wrote in message
news:XA****************@newsread1.news.atl.earthli nk.net...
Is it possible to set the Math functions to use
degrees instead of radians?

<snip>

No.

But, depending on what you are doing you could still work in degrees. If
you were interested in say sine and cosine values in increments of whole
degrees you could create your own look-up tables:-

var sinTable = [];
var cosTable = [];
var degToRads = Math.PI/180;
for(var c = 0;c < 360;c++){
sinTable[c] = Math.sin(c*degToRads);
cosTable[c] = Math.cos(c*degToRads);
}

var sinOf_23 = sinTable[23];

- but that only really works if you can get away with only using whole
degree steps. It could be expanded to say quarter degree steps but then
the work of converting a floating-point value into an integer Array
index (multiplying by 4 and rounding/flooring) would be similar to the
work required to convert degrees to radians.

I suppose the next option would be to create an object that had similar
functions to the Math object that wrapped calls to the real Math object
methods in code that did the degree to radians conversion for you:-

var degreeMath = (function(){
var m = Math;
var degToRads = (m.PI/180);
return ({
acos:function(n){
return (m.acos(n)/degToRads);
},
asin:function(n){
return (m.asin(n)/degToRads);
},
atan:function(n){
return (m.atan(n)/degToRads);
},
atan2:function(y, x){
return (m.atan2(y, x)/degToRads);
},
cos:function(d){
return m.cos(d*degToRads);
},
sin:function(d){
return m.sin(d*degToRads);
},
tan:function(d){
return m.tan(d*degToRads);
}
});
})();

var sinOf_23 = degreeMath.sin(23);

-but that has got to be relatively inefficient. It would probably be
better to bite the bullet and write the code to work with radians
instead of degrees.

Richard.
Jul 20 '05 #6

P: n/a
Fox


Jeff Thies wrote:

Is it possible to set the Math functions to use degrees instead of
radians?

I'm working out some astronomical calculations and everything is in
degrees. All those conversions are driving me a bit crazy!

Jeff

When converting from degrees to radians, you are introducing a fair
amount of rounding error -- don't think for a minute you're getting the
16 digit accuracy JS attempts to deliver. At best, you get, maybe,
reliably 12-13, but you can push it a little at about 14 digits.

You cannot prototype the Math object -- that feature was either
overlooked or its lack was intended to dissuade people from making
changes or additions to the object...however, JS being what it is... you
can just "glom" on whatever you want... the "this" refers to Math. All
the following have been adjusted to trim the precision a couple of
places (I hate it when IE says the Sin of 30 degrees is
0.4999999999999998).

The "degrees version" of the trig functions are Capitalized as opposed
to the radian versions (for simplification).

Also for simplification, I've used 'with (this)' to remove the necessity
of repeatedly typing "Math." or "this.", so, sin means Math.sin (or
this.sin) and PI means Math.PI, etc...

The precision correction is set up this way to try to provide a small
performance boost (over repeatedly calling the expanded form) -- set the
desired precision at the beginning of your script -- there will be some
instances where you might want to reduce the precision to about 12 (for
example, take the sine of a number, then perform Asin -- there will be
more error introduced:: Math.Asin(Math.Sin(18)) returns
18.00000000000016 -- first get the result of the computation, then set
the precision to 12 to trim it back to 18, then reset the precision back
to 14).
Math.setPrecision = function(digits) {
this._prec = this.pow(10, this.round(digits)); // cannot have
fractional digits
}
Math.setPrecision(14);

Math.toPrecision = function(x) { with(this) return round(x *
_prec)/_prec; }

Math._2rad = Math.PI/180;
Math._2deg = 180/Math.PI;

Math.Sin = function(x) { with(this) return toPrecision(sin(x * _2rad)); }
Math.Cos = function(x) { with(this) return toPrecision(cos(x * _2rad)); }
Math.Tan = function(x) { with(this) return toPrecision(tan(x * _2rad)); }

Math.Atan2 = function(a, b)
{ with(this) return toPrecision(atan2(a * _2rad, b * _2rad) *
_2deg); }

Math.Asin = function(x) { with(this) return toPrecision(asin(x) *
_2deg); }
Math.Acos = function(x) { with(this) return toPrecision(acos(x) *
_2deg); }

These should serve as model enough for you to carry out the rest...
Good luck with your astronomy... The precision of JS isn't really up to
the task of remarkable accuracy, but it will get close enough to be
useful to backyard astronomers...
Jul 20 '05 #7

P: n/a
JRS: In article <3F***************@spam.com>, seen in
news:comp.lang.javascript, Fox <do**@spam.com> posted at Thu, 18 Dec
2003 22:36:30 :-
Jeff Thies wrote:

Is it possible to set the Math functions to use degrees instead of
radians?

I'm working out some astronomical calculations and everything is in
degrees. All those conversions are driving me a bit crazy!
When converting from degrees to radians, you are introducing a fair
amount of rounding error -- don't think for a minute you're getting the
16 digit accuracy JS attempts to deliver. At best, you get, maybe,
reliably 12-13, but you can push it a little at about 14 digits.
I do not at all see why that should be, provided that an accurate value
for Pi is used; and Math.PI appears accurate.

You cannot prototype the Math object -- that feature was either
overlooked or its lack was intended to dissuade people from making
changes or additions to the object...however, JS being what it is... you
can just "glom" on whatever you want... the "this" refers to Math. All
the following have been adjusted to trim the precision a couple of
places (I hate it when IE says the Sin of 30 degrees is
0.4999999999999998).


Does it? I find no numbers between 0.49999999999999994 and 0.5

Working in radians, except for I/O, should be quicker; however, I
suppose one could create a new Object called Deg with methods that use
Math internally.
--
John Stockton, Surrey, UK. ?@merlyn.demon.co.uk / ??*********@physics.org
Web <URL:http://www.merlyn.demon.co.uk/> - FAQish topics, acronyms, & links.
Correct <= 4-line sig. separator as above, a line precisely "-- " (SoRFC1036)
Do not Mail News to me. Before a reply, quote with ">" or "> " (SoRFC1036)
Jul 20 '05 #8

P: n/a
Fox wrote:
You cannot prototype the Math object -- that feature was either
overlooked
No.
or its lack was intended
Yes. It does not make sense to have more than one Math object.
to dissuade people from making changes or additions to the object...
No. You can add properties to Math as to any other object.
You can overwrite existing properties as well. See for example
http://pointedears.de.vu/scripts/math.js
Math.setPrecision = function(digits) {
this._prec = this.pow(10, this.round(digits)); // cannot have
fractional digits
}
Math.setPrecision(14);


You are already adding properties to the Math object and use them.
What else do you want? :)
PointedEars
Jul 20 '05 #9

P: n/a
Fox


Thomas 'PointedEars' Lahn wrote:

Fox wrote:
You cannot prototype the Math object -- that feature was either
overlooked
No.


You can prototype every other object, including Object (just about --
other exceptions: navigator, history)... so why not the Math object? The
error generated states that prototype is not a method of the object.
or its lack was intended
Yes. It does not make sense to have more than one Math object.


prototyping is not instantiation (which, by the way, can be done -- even
though Math has no constructor) -- but it *does* make sense to be able
to add custom functionality -- which *is* the purpose of prototype.
to dissuade people from making changes or additions to the object...
No. You can add properties to Math as to any other object.


The "standard" way is via prototype... (is my face turning blue?)
You can overwrite existing properties as well. See for example
http://pointedears.de.vu/scripts/math.js
I looked through this entire document...several times... and didn't see
one instance where a property (OR a method) of Math had been overwritten
-- help me out here -- what's overwritten?

I found all the following had an assignation:

Math.roundDigits
Math.gcd
Math.powInt
Math.power
Math.logN
Math.log2
Math.log10
Math.rec
Math.getPeriod
Math.root
Math.sqr
Math.cub
Math.cubrt
Math.dec2base
Math.randomNumber
Math.randomInteger
Math.binomCoeff

I don't recognize any of these as standard methods of the Math object
and I found no instance anywhere where any of the following standard
properties were reassigned (overwritten)

Math.E
Math.LN10
Math.LN2
Math.LOG10E
Math.LOG2E
Math.PI
Math.SQRT1_2
Math.SQRT2

Math.setPrecision = function(digits) {
this._prec = this.pow(10, this.round(digits)); // cannot have
fractional digits
}
Math.setPrecision(14);
You are already adding properties to the Math object and use them.


Yes I am -- have for years...
What else do you want? :)


I can be pretty dense sometimes -- I don't get this question. What else
*can* I do? I can add methods and properties and I can instantiate the
Math object. I can have the static "instance" remain the same and
customize the instantiated object to the hilt (and it is actually *safe*
to override methods in the copy since the original static Math is still
there for backside support).

What I want from Math is long double precision (64-bit). Just about
every platform has implemented it for at least the last 5 years (or
more!). With it, we could get considerably more precision. Astronomy
(solar system orbital mechanics) has been a long time programming
interest of mine (since the days of 8-bit processors). I want the
*option* to switch from standard 32-bit doubles to double precision long
doubles since it is not always necessary to run at such high precision
[sometimes I'll trade performance for precision.] It would be *nice* if
a selector option could be set so that trig functions would accept
either radian or degree arguments (or gradians). I would like a *native*
log (base 10) method. I would like *native* precision handlers (anything
scripted is considerably slower). I would like a native fixed point and
integer math package. How about Hyperbolic functions? Matrix operations?
.... ...
Jul 20 '05 #10

P: n/a
Fox <do**@spam.com> writes:
You can prototype every other object, including Object
Object is not an object[1], it is a function/constructor. It can be
used to create objects. You can change the prototype connected to
*those* objects.

Math, in comparison, is already an object, not a constructor. You
don't have access to its constructor or its prototype (well, actually
you do, because it's prototype is the same as for other objects
created from Object (check "Math instanceof Object").
(just about --
other exceptions: navigator, history)... so why not the Math object?
Both exceptions are also singular objects, not objects that there are
more than one of.
The error generated states that prototype is not a method of the
object.
Because it isn't. There is no Math.prototype, because Math is not
a function. It is an object.
prototyping is not instantiation (which, by the way, can be done -- even
though Math has no constructor) -- but it *does* make sense to be able
to add custom functionality -- which *is* the purpose of prototype.
What *is* prototyping to you?

To me, a prototype based object oriented language (as opposed to a class
based one) distinguishes itself in the way new objects are created.

In a class based language, new instances are based on a class.
In a prototype based language, new instances are based on an object.

That changing a property of the prototype of an object is also visible
on the object, is not a requirement. It is one way to implement it,
and the one often taken in dynamic languages where you can dynamically
add properties.

"Prototyping" is not distinct from instantiation to me, because
prototyping is describing how instantiation happens.
So, the purpose of prototyping is *not* to be able to add properties
to objects. It is the ability to make objects from other objects.

Adding properties to objects can be done directly on the objects.

The only place where prototyping and adding properties interact, is
when you want to add properties to several related objects at once.
There is only one Math object, so that is completely unnecessary.
No. You can add properties to Math as to any other object.


The "standard" way is via prototype... (is my face turning blue?)


I don't know, but you are wrong.
The "standard" way (if any such exist) to add properties to an
object, is by assigning it directly to the object.
I looked through this entire document...several times... and didn't see
one instance where a property (OR a method) of Math had been overwritten
-- help me out here -- what's overwritten?
I don't know, didn't check the page. But if you dind't find it, then
make it yourself:
function changeMath() {
var oldPI = Math.PI;
var oldSin = Math.sin;
Math.PI = 3;
Math.sin = function(tr) {return oldSin(tr/3*oldPI);};
}

changeMath();
alert([Math.sin(Math.PI),
Math.cos(Math.PI)]);
// normally alerts 0,-1
// now alerts -0.1477...,-1
// because Math.sin is changed but Math.PI is read only.
I can be pretty dense sometimes -- I don't get this question. What else
*can* I do?
Ok, why do you want to do it differently?
I can add methods and properties and I can instantiate the
Math object.
No, you never instantiated the Math object. It is not a constructor.
I can have the static "instance" remain the same and
customize the instantiated object to the hilt (and it is actually *safe*
to override methods in the copy since the original static Math is still
there for backside support).
Yes, that is fairly simple:

function cloneMath() {
function nop(){};
nop.prototype = Math;
return new nop();
}

What I want from Math is long double precision (64-bit). Just about
every platform has implemented it for at least the last 5 years (or
more!).
Numbers in ECMAScript are 64-bit double precission IEEE-754 numbers.
I don't know what the difference between that and 64-bit "long double"
is.
With it, we could get considerably more precision. Astronomy
(solar system orbital mechanics) has been a long time programming
interest of mine (since the days of 8-bit processors). I want the
*option* to switch from standard 32-bit doubles to double precision long
doubles since it is not always necessary to run at such high precision
[sometimes I'll trade performance for precision.] It would be *nice* if
a selector option could be set so that trig functions would accept
either radian or degree arguments (or gradians).
That should be possible, but you can do that yourself too. Not as
efficiently, ofcourse.

Math.inputMode = 0; // 0 is radians, 1 is degress:
function dispatch(func) {
return function(n){switch (this.inputMode) {
case 1: return this.call(func,n/180*Math.PI);
default: return this.call(func,n);
}};
}
Math.sin = dispatch(Math.sin);
Math.cos = dispatch(Math.cos);
Math.tan = dispatch(Math.tan);
I would like a *native* log (base 10) method.

Is the efficiency of:
Math.log10 = function(n) {return Math.log(n)*Math.LOG10E;}
that bad?
I would like *native* precision handlers (anything
scripted is considerably slower). I would like a native fixed point and
integer math package. How about Hyperbolic functions? Matrix operations?


You want more. No problem with that :) You just shouldn't hold your
breath waiting for a high-performance super math package to be
implemented in a browser scripting language. It's not that much in
demand.

/L
--
Lasse Reichstein Nielsen - lr*@hotpop.com
DHTML Death Colors: <URL:http://www.infimum.dk/HTML/rasterTriangleDOM.html>
'Faith without judgement merely degrades the spirit divine.'
Jul 20 '05 #11

P: n/a
Lasse Reichstein Nielsen <lr*@hotpop.com> writes:
Fox <do**@spam.com> writes:
You can prototype every other object, including Object
Object is not an object[1], it is a function/constructor.


and the missing footnote should say
[1] ... except that functions are objects too, and their prototype is
Function.prototype.

/L--

Lasse Reichstein Nielsen - lr*@hotpop.com
DHTML Death Colors: <URL:http://www.infimum.dk/HTML/rasterTriangleDOM.html>
'Faith without judgement merely degrades the spirit divine.'
Jul 20 '05 #12

P: n/a
Fox wrote:
Thomas 'PointedEars' Lahn wrote:
Fox wrote:
You can overwrite existing properties as well. See for example
http://pointedears.de.vu/scripts/math.js
I looked through this entire document...several times... and didn't see
one instance where a property (OR a method) of Math had been overwritten
-- help me out here -- what's overwritten?


Until now? Nothing. I referred to the previous sentence, note the context.
I don't recognize any of these as standard methods of the Math object
Would I need to define them then?
and I found no instance anywhere where any of the following standard
properties were reassigned (overwritten)


Of course. Why reinventing the wheel?
PointedEars
Jul 20 '05 #13

P: n/a
JRS: In article <3F***************@spam.com>, seen in
news:comp.lang.javascript, Fox <do**@spam.com> posted at Sat, 20 Dec
2003 00:41:53 :-
What I want from Math is long double precision (64-bit).
You already have, in standard javascript, all numbers being IEEE 64-bir
Doubles, with 53 bits of numeric resolution. Have you not seen FAQ 4.7?

Or do you mean the 80-bit type, called "extended" in Pascal & Delphi?

Just about
every platform has implemented it for at least the last 5 years (or
more!). With it, we could get considerably more precision. Astronomy
(solar system orbital mechanics) has been a long time programming
interest of mine (since the days of 8-bit processors). I want the
*option* to switch from standard 32-bit doubles
What could standard 32-bit doubles be? IEEE singles are 32-bit, with 24
bits of resolution.
to double precision long
doubles since it is not always necessary to run at such high precision
[sometimes I'll trade performance for precision.] It would be *nice* if
a selector option could be set so that trig functions would accept
either radian or degree arguments (or gradians). I would like a *native*
log (base 10) method. I would like *native* precision handlers (anything
scripted is considerably slower). I would like a native fixed point and
integer math package. How about Hyperbolic functions? Matrix operations?

The proportion of javascript-enabled browser users who would be
interested in pages using that is very small.

The proportion of javascript authors who can use Math to the full is
very small.

The proportion of those who cannot implement those functions themselves,
or need speed greater that self-implementing would produce, is
insignificant - it is commercially-negligible. Therefore, you should
not expect to see it come.

The only omission that would make commercial sense to rectify is the
lack of an ECMA-standard means to convert from Number to given-length
String with a given number of decimal places shown; for that, see the
FAQ.
Please give a proper name - we are accustomed to seeing Fox Mahoney
here, and posting as Fox can cause confusion.

--
John Stockton, Surrey, UK. ?@merlyn.demon.co.uk Turnpike v4.00 IE 4
<URL:http://jibbering.com/faq/> Jim Ley's FAQ for news:comp.lang.javascript
<URL:http://www.merlyn.demon.co.uk/js-index.htm> jscr maths, dates, sources.
<URL:http://www.merlyn.demon.co.uk/> TP/BP/Delphi/jscr/&c, FAQ items, links.
Jul 20 '05 #14

P: n/a
Fox


Thomas 'PointedEars' Lahn wrote:

Fox wrote:
Thomas 'PointedEars' Lahn wrote:
Fox wrote:
You can overwrite existing properties as well. See for example
http://pointedears.de.vu/scripts/math.js
I looked through this entire document...several times... and didn't see
one instance where a property (OR a method) of Math had been overwritten
-- help me out here -- what's overwritten?


Until now? Nothing.


Then how is math.js an example?
I referred to the previous sentence, note the context.
I did -- it says: you can overwrite existing properties as well. See
for example [url...]

In context, it looks like you meant to show me examples of overwriting
existing properties...

I *still* read it that way...
I don't recognize any of these as standard methods of the Math object
Would I need to define them then?


only if you had actually overridden them...
and I found no instance anywhere where any of the following standard
properties were reassigned (overwritten)
Of course. Why reinventing the wheel?


you had me going there for awhile...

PointedEars

Jul 20 '05 #15

P: n/a
Fox


Lasse Reichstein Nielsen wrote:

Fox <do**@spam.com> writes:
You can prototype every other object, including Object
Object is not an object[1], it is a function/constructor. It can be
used to create objects. You can change the prototype connected to
*those* objects.


I think you confuse the method 'prototype' with the abstract concept of
"a prototype" or the definition of the constructor function.

To quote Netscape documentation:

"You can use the prototype to add properties or methods to all instances
of a class."

Oh -- and Object IS an object and it CAN be prototyped (as in, having
functionality added):

Object.prototype.something = function() { alert(this + "\nthis is
something"); }

function
test()
{
this.prop = "test";
}

var t = new test();

t.something(); // shows alert "[object Object] this is something"

(25).something(); // shows alert "25 this is something"

etc...

something() is automatically inherited by EVERY instantiated object (and
object literal) after prototyping...

this is interesting:

Math.something() will display an alert [object Math] this is
something... (Not navigator or history, though, or any other object
"constructed" before the prototyping [like DOM objects]).

Math, in comparison, is already an object, not a constructor. You
don't have access to its constructor or its prototype (well, actually
you do, because it's prototype is the same as for other objects
created from Object (check "Math instanceof Object").
Math is a static class -- it has no constructor. It also has no
prototype method... you cannot:

Math.prototype.something

which is what I meant in my original statement.
(just about --
other exceptions: navigator, history)... so why not the Math object?
Both exceptions are also singular objects, not objects that there are
more than one of.


Both are static classes...no constructors...[I believe there are also
some "locks" on these, particularly history because of security concerns]
The error generated states that prototype is not a method of the
object.
Because it isn't. There is no Math.prototype, because Math is not
a function. It is an object.


okay, i'm getting bored.
prototyping is not instantiation (which, by the way, can be done -- even
though Math has no constructor) -- but it *does* make sense to be able
to add custom functionality -- which *is* the purpose of prototype.
What *is* prototyping to you?


Just as the documentation has defined it:
to add properties or methods to all instances of a class

To me, a prototype based object oriented language (as opposed to a class
based one) distinguishes itself in the way new objects are created.
No it doesn't... nothing distinguishing about it... it's just a
different approach -- the constructor IS the "class".
In a class based language, new instances are based on a class.
In a prototype based language, new instances are based on an object.
so far, the only difference is the use of the keyword "class" and an
internal constructor in a class, and the lack of one in a
prototyped-based OO language.

in a class-based language, new instances are objects -- storage is
allocated -- properties initialized -- methods placed in a "pool" (they
will not be declared again -- they are shared amongst all instances of
the class)

in a prototype-based language: new instances are objects -- storage is
allocated -- properties initialized -- methods placed in a pool
[supposedly] (they will not be declared again -- they are shared amongst
all instances of the main constructor -- whatever that might be at a
given time). Prototyping, under certain circumstances, is a way for us
to overload a "class" declaration. For example:

function
Car(arg)
{
this.make = arg;
}

function
Ford(arg)
{
this.model = arg;
}

Ford.prototype = new Car("Ford");

function
Chevy(arg)
{
this.model = arg;
}

Chevy.prototype = new Car("Chevy");

function
Other(arg1,arg2)
{
this.country = arg1;
this.manufacturer = arg2;
}

Other.prototype = new Car("Foreign");
if we instantiate Ford or Chevy, then the resultant object is Car with
make and model properties. However, if we instantiate Other, then the
resultant object is Car with make, country, and manufacturer properties.

Overloading constructors is available in class-based languages, but the
prototype-based version is more flexible and powerful because only those
properties or methods required for that particular object instance are
created. In a class-based language, every possible property or method
that could be used must be declared.


That changing a property of the prototype of an object is also visible
on the object, is not a requirement. It is one way to implement it,
and the one often taken in dynamic languages where you can dynamically
add properties.
This is where the true power of the prototype-based OO language
lies...absolute flexibility.. the ability to "morph" objects as you go
along (including core language objects).


"Prototyping" is not distinct from instantiation to me, because
prototyping is describing how instantiation happens.
yeah... i disagree -- the *constructor* describes how instantiation happens...

prototyping *changes* how instantiation happens -- when methods or
properties are prototyped to an object -- nothing in the rest of the
program changes... IF, and only if instantiation occurs (invoking a
constructor) will there be an affect.
So, the purpose of prototyping is *not* to be able to add properties
to objects.
That's *exactly* the purpose of prototyping...
It is the ability to make objects from other objects.
adequately illustrated above...except that the objects and "other
objects" become one object (more like class/subclass).

One other thing:

even if you write a function to be a constructor for objects, it does
not make that the same object as those that would be instantiated from
it. In other words, the constructor exists as an instance of the
Function object (and as a member of the instantiated object), it is not,
for instance, a "Car" object (to use the above as an example)...those
will not exist until they are individually instantiated.


Adding properties to objects can be done directly on the objects.
Yeah --

The only place where prototyping and adding properties interact, is
when you want to add properties to several related objects at once.
There is only one Math object, so that is completely unnecessary.
There is only one String object, one Number object, one Array object,
etc... and yet, prototype is a method of those objects... it is
unnecessary because Math is not intended to be instantiated... but that
doesn't mean that, for consistency, it couldn't be used syntactically in
the same manner as these other core objects.
No. You can add properties to Math as to any other object.
The "standard" way is via prototype... (is my face turning blue?)


I don't know, but you are wrong.

The "standard" way (if any such exist) to add properties to an
object, is by assigning it directly to the object.
poor programming habits are rampant in JS programmers. The FAQ uses
prototype where appropriate (and correctly), not that I would tout the
faq as a guideline for programming style convention. However, that
flexibility exists, and it is anyone's prerogative to do so. In the case
of Math, it is a necessity.
I looked through this entire document...several times... and didn't see
one instance where a property (OR a method) of Math had been overwritten
-- help me out here -- what's overwritten?
I don't know, didn't check the page. But if you dind't find it, then
make it yourself:


NOT ME -- the guy I was replying to claimed he had overwritten methods
in Math. Personally, I wouldn't care to do such a thing. There's nothing
that could be scripted that would be more efficient than what is available...

function changeMath() {
var oldPI = Math.PI;
var oldSin = Math.sin;
Math.PI = 3;
Math.sin = function(tr) {return oldSin(tr/3*oldPI);};
}

changeMath();
alert([Math.sin(Math.PI),
Math.cos(Math.PI)]);
// normally alerts 0,-1
// now alerts -0.1477...,-1
// because Math.sin is changed but Math.PI is read only.
I can be pretty dense sometimes -- I don't get this question. What else
*can* I do?
Ok, why do you want to do it differently?


Do what differently? that section didn't make any sense to me.
I can add methods and properties and I can instantiate the
Math object.
No, you never instantiated the Math object. It is not a constructor.


I didn't say I did instantiate the Math object... I know it's not a
constructor... I just said I could... I see you know how also... big deal.
I can have the static "instance" remain the same and
customize the instantiated object to the hilt (and it is actually *safe*
to override methods in the copy since the original static Math is still
there for backside support).
Yes, that is fairly simple:

function cloneMath() {
function nop(){};
nop.prototype = Math;
return new nop();
}
What I want from Math is long double precision (64-bit). Just about
every platform has implemented it for at least the last 5 years (or
more!).


Numbers in ECMAScript are 64-bit double precission IEEE-754 numbers.
I don't know what the difference between that and 64-bit "long double"
is.


I was wrong (I'm tired and stressed)... I meant 96-bit long doubles that
are available in C (at least in some compilers). It's been several years
since I've worked in C, so... I had to go back and look it
up...something I should have done before i made the statement.
With it, we could get considerably more precision. Astronomy
(solar system orbital mechanics) has been a long time programming
interest of mine (since the days of 8-bit processors). I want the
*option* to switch from standard 32-bit doubles to double precision long
doubles since it is not always necessary to run at such high precision
[sometimes I'll trade performance for precision.] It would be *nice* if
a selector option could be set so that trig functions would accept
either radian or degree arguments (or gradians).
That should be possible, but you can do that yourself too. Not as
efficiently, ofcourse.


That's the point -- efficiency... core routines exposed to js are much
more efficient than code we script.


Math.inputMode = 0; // 0 is radians, 1 is degress:
function dispatch(func) {
return function(n){switch (this.inputMode) {
case 1: return this.call(func,n/180*Math.PI);
default: return this.call(func,n);
}};
}
Math.sin = dispatch(Math.sin);
Math.cos = dispatch(Math.cos);
Math.tan = dispatch(Math.tan);
I would like a *native* log (base 10) method.
Is the efficiency of:
Math.log10 = function(n) {return Math.log(n)*Math.LOG10E;}
that bad?


Depends on how many times the function (or this in conjunction with many
other functions) needs to be iterated (and in some applications, that
could be hundreds or more times in a single loop). Extra (scripted) fp
multiplies tend to be a drag.

It's somewhat ridiculous that log base 10 is not available in the core language.
I would like *native* precision handlers (anything
scripted is considerably slower). I would like a native fixed point and
integer math package. How about Hyperbolic functions? Matrix operations?
You want more. No problem with that :) You just shouldn't hold your
breath waiting for a high-performance super math package to be
implemented in a browser scripting language. It's not that much in
demand.


no sh**.


/L
--
Lasse Reichstein Nielsen - lr*@hotpop.com
DHTML Death Colors: <URL:http://www.infimum.dk/HTML/rasterTriangleDOM.html>
'Faith without judgement merely degrades the spirit divine.'

Jul 20 '05 #16

P: n/a
Fox


Dr John Stockton wrote:

JRS: In article <3F***************@spam.com>, seen in
news:comp.lang.javascript, Fox <do**@spam.com> posted at Sat, 20 Dec
2003 00:41:53 :-
What I want from Math is long double precision (64-bit).
You already have, in standard javascript, all numbers being IEEE 64-bir
Doubles, with 53 bits of numeric resolution. Have you not seen FAQ 4.7?


Yeah I have -- the accuracy is only 14 significant digits, not decimal
digits -- it's two different things and is precisely the issue of how
numbers are stored in a floating point processor [similar to scientific
notation -- where there is an implied one and the rest are (52) binary
bits representing the fractional part from there...with 11 exponent bits
and a sign bit]. With an FPU, you can accurately represent a number like
1e-300, or 9.847385948392e-245, but you cannot accurately represent a
number like:

123400000.00000000134341 -- too many significant digits.

anything past 14 significant digits is just "binary noise" that doesn't
translate to decimal.


Or do you mean the 80-bit type, called "extended" in Pascal & Delphi?
I actaully meant 96 bit long doubles as defined in the Metrowerks C
compiler (fp.h) (Mac, at least, not sure about PC).
I got ahead of myself (and i actually had to look it up in the header
files)...I also used to work quite a bit with fixed point integer math
and was writing a 64-bit version...probably what i got "stuck" on -- OR
-- I associated the resolution of the fp's with older 32-bit machines as
opposed to newer 64-bit machines -- long doubles more or less came into
existence with the 64-bit machines (or 32/64's).

96-bit long doubles would translate into, roughly, an extra 4 or 5
(accurate) significant (decimal) digits.

It's not like we have any choices in JS as we do in other languages.
Thing is: I said long double and meant long double...however many bits
there are in JS floating point numbers is unimportant... they're still
not enough for "accurate" astronomy (just "close enough"). It was an
unfortunate mistake.
Just about
every platform has implemented it for at least the last 5 years (or
more!). With it, we could get considerably more precision. Astronomy
(solar system orbital mechanics) has been a long time programming
interest of mine (since the days of 8-bit processors). I want the
*option* to switch from standard 32-bit doubles
What could standard 32-bit doubles be? IEEE singles are 32-bit, with 24
bits of resolution.


same problem as above -- just adjusted down...
at this point, it's an obvious mistake... you just like rubbing it in?

to double precision long
doubles since it is not always necessary to run at such high precision
[sometimes I'll trade performance for precision.] It would be *nice* if
a selector option could be set so that trig functions would accept
either radian or degree arguments (or gradians). I would like a *native*
log (base 10) method. I would like *native* precision handlers (anything
scripted is considerably slower). I would like a native fixed point and
integer math package. How about Hyperbolic functions? Matrix operations?


The proportion of javascript-enabled browser users who would be
interested in pages using that is very small.

perhaps... or maybe they're just resigned to the status quo.
The proportion of javascript authors who can use Math to the full is
very small.
no doubt...

The proportion of those who cannot implement those functions themselves,
or need speed greater that self-implementing would produce, is
insignificant - it is commercially-negligible. Therefore, you should
not expect to see it come.
didn't say i ever expected it -- just what *i* would like.

The only omission that would make commercial sense to rectify is the
lack of an ECMA-standard means to convert from Number to given-length
String with a given number of decimal places shown; for that, see the
FAQ.
that's a formatting issue for the end of calculations...not really a
critical speed issue.

Please give a proper name - we are accustomed to seeing Fox Mahoney
here, and posting as Fox can cause confusion.

it's not like you know me personally...what difference does it make?

--
John Stockton, Surrey, UK. ?@merlyn.demon.co.uk Turnpike v4.00 IE 4
<URL:http://jibbering.com/faq/> Jim Ley's FAQ for news:comp.lang.javascript
<URL:http://www.merlyn.demon.co.uk/js-index.htm> jscr maths, dates, sources.
<URL:http://www.merlyn.demon.co.uk/> TP/BP/Delphi/jscr/&c, FAQ items, links.

Jul 20 '05 #17

P: n/a
Fox


Dr John Stockton wrote:

JRS: In article <3F***************@spam.com>, seen in
news:comp.lang.javascript, Fox <do**@spam.com> posted at Thu, 18 Dec
2003 22:36:30 :-
Jeff Thies wrote:

Is it possible to set the Math functions to use degrees instead of
radians?

I'm working out some astronomical calculations and everything is in
degrees. All those conversions are driving me a bit crazy!
When converting from degrees to radians, you are introducing a fair
amount of rounding error -- don't think for a minute you're getting the
16 digit accuracy JS attempts to deliver. At best, you get, maybe,
reliably 12-13, but you can push it a little at about 14 digits.


I do not at all see why that should be, provided that an accurate value
for Pi is used; and Math.PI appears accurate.


last i heard -- pi had over a billion digits and counting... you cannot
depend on the accuracy of JS past 14 significant digits.
You cannot prototype the Math object -- that feature was either
overlooked or its lack was intended to dissuade people from making
changes or additions to the object...however, JS being what it is... you
can just "glom" on whatever you want... the "this" refers to Math. All
the following have been adjusted to trim the precision a couple of
places (I hate it when IE says the Sin of 30 degrees is
0.4999999999999998).
Does it? I find no numbers between 0.49999999999999994 and 0.5


okay -- i was winging it --

however:

0.49999999999999990 + 0.00000000000000001 => 0.49999999999999999 (so
there is one)


Working in radians, except for I/O, should be quicker; however, I
suppose one could create a new Object called Deg with methods that use
Math internally.
OP didn't want radians... most (but not all) astronomy books use
degrees... Meeus does, and so does Duffett-Smith (if memory serves) --
the two most likely sources for amateurs writing astronomical calculators.

Meeus devotes an entire chapter in Astronomical Algorithms to the
accuracy of calculators and computers... all the data he supplies has
only 10 significant digits (in most places) or fewer. No calculation
using more significant digits can yield any more accuracy than the data
with which one starts.


--
John Stockton, Surrey, UK. ?@merlyn.demon.co.uk / ??*********@physics.org
Web <URL:http://www.merlyn.demon.co.uk/> - FAQish topics, acronyms, & links.
Correct <= 4-line sig. separator as above, a line precisely "-- " (SoRFC1036)
Do not Mail News to me. Before a reply, quote with ">" or "> " (SoRFC1036)

Jul 20 '05 #18

P: n/a
Fox <do**@spam.com> writes:
Lasse Reichstein Nielsen wrote: I think you confuse the method 'prototype' with the abstract concept of
"a prototype" or the definition of the constructor function.
There is no method called "prototype" (where I use "method" to mean
"is a property of an object and is a function").

Are you thinking about the "prototype" property of functions?
To quote Netscape documentation:

"You can use the prototype to add properties or methods to all instances
of a class."
I disagree with the way it is written. For one thing, I don't like to use
the word "class" about a objects in a prototype base language. But, for
now, let's use the word "class" about a constructor (i.e., a function)
and "instance of a class" about the objects that satsify "obj instanceof
classFunction").
Oh -- and Object IS an object and it CAN be prototyped (as in, having
functionality added):
The global constructor "Object" is a function, and as such an object.

If you treat it as a constructor (a "class"), you can add properties
to its instances by adding properties to its prototype object.
I take it that is what you mean by "be prototyped".

That does not add functionality to Object, but only to its instances.
(So, I'm arguing that your way of saying it is imprecise, although
your meaning is probably correct)

.... something() is automatically inherited by EVERY instantiated object (and
object literal) after prototyping...
Yes. It becomes a property of the original object prototype, which is in
the prototype chain of all language objects.
this is interesting:

Math.something() will display an alert [object Math] this is
something... (Not navigator or history, though, or any other object
"constructed" before the prototyping [like DOM objects]).
I think that is merely because the objects referenced by "navigator",
"history", and the DOM Nodes are host objects, which don't
(necessarily) have the original object prototype in their prototype
chain.

All language objects will have "something" as an inherited method,
also those created before.

Try:
---
function something() {alert (this + " is something!");}
var x = new String("foo"); // or just the equivalent, var x = {};
var d = document.createElement("div"):
alert(typeof x.something);
alert(typeof d.something);
Object.prototype.something = something;
alert(typeof x.something); // old object
alert(typeof d.something); // old host object
var x = new String("foo"){
var d = document.createElement("div"):
alert(typeof x.something); // new object
alert(typeof d.something); // new host object
---

In IE, the DOM div node will never have something as a property.
In Opera 7, it does inherit from Object.prototype, so it seems it
is browser dependent how host objects behave.
Math is a static class -- it has no constructor.
There are no classes in a prototype based language. If we use the name
"class" for functions that are used as constructors, then that's just
words to make us happy. There is definitly no such thing as a "static
class". Math is an *object*. Nothing more, nothing less. There is no
significant difference between Math and any object with the same properties.

---
var Math2 = new Object;
for(var i in Math) {Math2[i]=Math[i];}
---
That gives you a new "Math" object with exactly the same properties as
the old one. The only difference is that some of the properties of Math
are read-only, but it is still just an object.
It also has no prototype method... you cannot:
There is no prototype "method".
Math.prototype.something
No, because "Math" refers to a non-function object.
All functions have a prototype property. Non-function objects don't.
Nothing to do with classes.
which is what I meant in my original statement.
Yes. It has no "prototype" property. Nor does Math2.
Both are static classes...no constructors...[I believe there are also
some "locks" on these, particularly history because of security concerns]
Both are objects. No more, no less (host objects, though, so they can act
different from language objects).
Because it isn't. There is no Math.prototype, because Math is not
a function. It is an object.

What *is* prototyping to you?


Just as the documentation has defined it:
to add properties or methods to all instances of a class


Ok, that was what I thought.
Math is not a class (there is no such thing as a static class). SO,
it cannot be prototyped (apart from prototyping the Object class).
To me, a prototype based object oriented language (as opposed to a class
based one) distinguishes itself in the way new objects are created.


No it doesn't... nothing distinguishing about it... it's just a
different approach -- the constructor IS the "class".


I disagree. I think that is an attempt to make a non-class based language
fit into a class based perception.
In a class based language, new instances are based on a class.
In a prototype based language, new instances are based on an object.


so far, the only difference is the use of the keyword "class" and an
internal constructor in a class, and the lack of one in a
prototyped-based OO language.


If classes are objects, yes.
in a class-based language, new instances are objects -- storage is
allocated -- properties initialized -- methods placed in a "pool" (they
will not be declared again -- they are shared amongst all instances of
the class)
That is an implementation method. It is not necessarily the only one,
but it has shown itself to be efficient.
At the conceptual level, the methods are properties of the object
just as fields are.
in a prototype-based language: new instances are objects -- storage is
allocated -- properties initialized -- methods placed in a pool
[supposedly] (they will not be declared again -- they are shared amongst
all instances of the main constructor -- whatever that might be at a
given time).
In Javascript, methods are no different from other properties. No pool,
just a reference from the object.
Ok. The reason I don't think it is correct to associate the constructor
to the "class" is that whether an object is an instance of a constructor
function can change.

Example:
---
function Foo(){}
var f = new Foo();
Foo.prototype = new Object();
alert(f instanceof Foo);
---
This alerts "false"!

The object in "f" was created with "new Foo()", but still it is not an
instance of "Foo".
The constructor doesn't define the "class"! The *prototype object* of
the constructor, at the time the object is created, defines the class.

Example:
---
function Foo(){} // Constructor Foo
function Bar(){} // Constructor Bar
var f = new Foo();
var b = new Bar();
var oldFooProt = Foo.prototype;
Foo.prototype = Bar.prototype;
var fb = new Foo();
Foo.prototype = oldFooProt;
// now guess the result of:
alert([f instanceof Foo,f instanceof Bar])
alert([b instanceof Foo,b instanceof Bar])
alert([fb instanceof Foo,fb instanceof Bar])
---

Here "fb" is created from the constructor "Foo", but it is an instance
of the (almost) unrelated constructor "Bar". Why? Because Bar's prototype
property refers to an object that is in fb's prototype chain.
The constructor doesn't define the class. The prototype object does.

That is what I mean by the difference between class based and
prototype based languages.
In a class based language, the class (object/definition) defines the
instances of the class.
In a prototype based language, any object defines a "class" of the
objects that are instances of it.

Javascript attempts to hide this using constructor functions, but
that's just wrapper. What really goes on below is inheritance between
an object (the prototype object of the constructor at the time) and
a new object. The constructor itself is just some function that is
not related to the inheritance. It's just a language gimmick to
enable prototype-inheritance between objects.

The clone method I previously posted would also work in general:
---
Object.prototype.clone = function(){
function nop(){}; // dummy function to facilitate inheritance
nop.prototype = this;
return new nop();
}
Object.prototype.instanceOf = function (obj) {
function nop(){};
nop.prototype = obj;
return this instanceof nop;
}
var rootObject = Object.prototype;
---
Then you can write:
---
var o1 = rootObject.clone(); // new object
var o2 = rootObject.clone(); // new object
var o3 = o1.clone(); // new instance of first object
o1.foo = 42; // extend first object/prototype of third
alert([o3.foo, o3.instanceOf(o1), o3.instanceOf(o2)]);
---

That is pure prototype based object oriented programming (I believe it
is closer to how it is done in the language Self). As you can see, the
actual constructor functions are irrelevant, inheritance still works,
instanceOf works, all because the actual prototype inheritance happens
between the *objects*. The constructors, the "classes", are just
scaffolds for the actual construction of objects.
There is only one Math object, so that is completely unnecessary.


There is only one String object, one Number object, one Array object,
etc... and yet, prototype is a method of those objects... it is
unnecessary because Math is not intended to be instantiated... but that
doesn't mean that, for consistency, it couldn't be used syntactically in
the same manner as these other core objects.


Except that it makes little sense to create more than one Math object,
since none of the "methods" operate on the object. You are correct that
one would most likely create Math as a static class in a class based
language, but that is because the class based language lacks a better
way to create a namespace - which is what you really want. In Standard
ML, it would be a module, which is just a namespace that can be opened
or accessed. In Javascript, it is an object, which is slightly more than
just a mapping from name to values.
The "standard" way (if any such exist) to add properties to an
object, is by assigning it directly to the object.


poor programming habits are rampant in JS programmers. The FAQ uses
prototype where appropriate (and correctly), not that I would tout the
faq as a guideline for programming style convention. However, that
flexibility exists, and it is anyone's prerogative to do so. In the case
of Math, it is a necessity.


Adding a property to the prototype of a number of instances saves space
compared to adding it to each (and adds flexibility to change it later).

Adding a property to one object is best done by adding it directly to
the object.

I don't think you can generalize and say that one is always better than
the other. It depends on the actual case.
> I can be pretty dense sometimes -- I don't get this question. What else
> *can* I do?


Ok, why do you want to do it differently?


Do what differently? that section didn't make any sense to me.


And I cut the context, so I can't remember what I was replying to.
Damn! It made sense when I wrote it.
I was wrong (I'm tired and stressed)... I meant 96-bit long doubles that
are available in C (at least in some compilers). It's been several years
since I've worked in C, so... I had to go back and look it
up...something I should have done before i made the statement.


Numbers get awfully big. I too remember when 16 bit computers were a
fantastic progress :)

/L
--
Lasse Reichstein Nielsen - lr*@hotpop.com
DHTML Death Colors: <URL:http://www.infimum.dk/HTML/rasterTriangleDOM.html>
'Faith without judgement merely degrades the spirit divine.'
Jul 20 '05 #19

P: n/a
JRS: In article <3F***************@spam.com>, seen in
news:comp.lang.javascript, Fox <do**@spam.com> posted at Sun, 21 Dec
2003 06:09:19 :-
Dr John Stockton wrote:

JRS: In article <3F***************@spam.com>, seen in
news:comp.lang.javascript, Fox <do**@spam.com> posted at Thu, 18 Dec
2003 22:36:30 :-
>Jeff Thies wrote:
>>
>> Is it possible to set the Math functions to use degrees instead of
>> radians?
>>
>> I'm working out some astronomical calculations and everything is in
>> degrees. All those conversions are driving me a bit crazy!

>When converting from degrees to radians, you are introducing a fair
>amount of rounding error -- don't think for a minute you're getting the
>16 digit accuracy JS attempts to deliver. At best, you get, maybe,
>reliably 12-13, but you can push it a little at about 14 digits.


I do not at all see why that should be, provided that an accurate value
for Pi is used; and Math.PI appears accurate.


last i heard -- pi had over a billion digits and counting... you cannot
depend on the accuracy of JS past 14 significant digits.

Pi has as many digits as one cares to calculate.

But I took your words to mean that conversion to radians introduces an
exceptional amount of error, more than for other simple operations.

Since basic astronomical angular data is probably no more accurate than
*about* a micro-radian, ISTM that a numerical accuracy of even 1 in 10^9
should be sufficient, if the algorithms are expressed prudently -
avoiding unnecessary subtraction of nearly equal numbers, for example.

--
John Stockton, Surrey, UK. ?@merlyn.demon.co.uk Turnpike v4.00 IE 4
<URL:http://jibbering.com/faq/> Jim Ley's FAQ for news:comp.lang.javascript
<URL:http://www.merlyn.demon.co.uk/js-index.htm> jscr maths, dates, sources.
<URL:http://www.merlyn.demon.co.uk/> TP/BP/Delphi/jscr/&c, FAQ items, links.
Jul 20 '05 #20

P: n/a
JRS: In article <3F***************@spam.com>, seen in
news:comp.lang.javascript, Fox <do**@spam.com> posted at Sun, 21 Dec
2003 06:06:33 :-

Please give a proper name - we are accustomed to seeing Fox Mahoney
here, and posting as Fox can cause confusion.


it's not like you know me personally...what difference does it make?

Because it is nice not to wonder whether you and Fox Mahoney are one
person or two persons. Should the present manifestation inherit the
reputation of the previous one, or not?

--
John Stockton, Surrey, UK. ?@merlyn.demon.co.uk Turnpike v4.00 MIME
Web <URL:http://www.uwasa.fi/~ts/http/tsfaq.html> -> Timo Salmi: Usenet Q&A.
Web <URL:http://www.merlyn.demon.co.uk/news-use.htm> : about usage of News.
No Encoding. Quotes before replies. Snip well. Write clearly. Don't Mail News.
Jul 20 '05 #21

This discussion thread is closed

Replies have been disabled for this discussion.