www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Best way to "convert" a real to ireal

reply =?ISO-8859-1?Q?Carsten_S=F8rensen?= <cso rift.dk> writes:
Hi,

With D's support for complex math I thought it would be fun to do a 
Mandelbrot explorer.

It's all working fine but in the process of writing it, a few questions 
popped into my head.

creal have .re and .im properties, but .im returns a real, not an ireal 
as I would expect. Is there another property that will return the 
imaginary part as an ireal? I can't seem to find the creal properties 
documented anywhere.

Since .im returns a real I sometimes have to convert it back to an ireal.

This doesn't work, im is now zero.
---
creal c = 1.0 + 1.0i;
ireal im = cast(ireal)c.im;
---

Instead I'm doing:
---
creal c = 1.0 + 1.0i;
ireal im = c.im * 1.0i;
---

but this seems a bit clumsy... is there a better way? Or better yet, a 
creal property that will actually retrieve the imaginary part as an ireal?


Thanks,
Carsten Sørensen
Sep 13 2007
parent reply Christian Kamm <kamm.incasoftware shift-at-left-and-remove-this.de> writes:
 creal have .re and .im properties, but .im returns a real, not an ireal
 as I would expect. Is there another property that will return the
 imaginary part as an ireal? I can't seem to find the creal properties
 documented anywhere.
I don't think there is. The properties are mentioned here http://www.digitalmars.com/d/property.html among the properties of floating point types, but not really documented. I expect .im behaves the way it does since that's how it's used in mathematics. So c.im * 1.0i is the right way to make it an ireal. Christian
Sep 13 2007
parent reply =?ISO-8859-1?Q?Carsten_S=F8rensen?= <cso rift.dk> writes:
Christian Kamm wrote:
 I don't think there is. The properties are mentioned here
 http://www.digitalmars.com/d/property.html
 among the properties of floating point types, but not really documented.
 
 I expect .im behaves the way it does since that's how it's used in
 mathematics. So c.im * 1.0i is the right way to make it an ireal.
Thanks for your reply! I suppose (well, hope really) the compiler does the right thing when multiplying by 1.0i. I just had a brainwave regarding the imaginary part of creal - --- creal c = 1.0 + 1.0i; ireal i = cast(ireal)c; --- does exactly what I want. Isn't it just obvious in hindsight... Best regards, Carsten Sørensen
Sep 13 2007
parent Christian Kamm <kamm.incasoftware shift-at-left-and-remove-this.de> writes:
 I just had a brainwave regarding the imaginary part of creal -
 
 ---
 creal c = 1.0 + 1.0i;
 ireal i = cast(ireal)c;
 ---
 
 does exactly what I want. Isn't it just obvious in hindsight...
For your peace of mind: with optimizations enabled, the cast(ireal) and the .im * i seem to produce exactly the same code. Cheers, Christian
Sep 14 2007